Advertisement
stronk_8s

mongoose crud

Sep 18th, 2024
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.16 KB | Source Code | 0 0
  1.  
  2. //db.ja
  3.  
  4. const mongoose = require('mongoose');
  5.  
  6. // async func because mongoose functions return promises
  7. const connectDB = async () => {
  8.     const con = await mongoose.connect("mongodb://localhost:27017/projectmgmt");
  9.     console.log(`MongoDB Connected: mongodb://localhost:27017/project`);
  10. };
  11.  
  12. module.exports = connectDB;
  13.  
  14.  
  15.  
  16. //models
  17. const clientSchema = new mongoose.Schema({
  18.     name: { type: String, required: true },
  19.     last: { type: String, required: true },
  20. });
  21.  
  22. const Client = mongoose.model('Client', clientSchema);
  23.  
  24.  
  25.  
  26. //insert
  27. const add = async (_, { name, last }) => {
  28.     const client = new Client({ name, last });
  29.     return await client.save();
  30. }
  31.  
  32. module.exports = add;
  33.  
  34.  
  35. //update
  36. const update = async (_, { id, name, last }) => {
  37.     return await Client.findByIdAndUpdate(id, { name, last }, { new: true });
  38. }
  39.  
  40. module.exports = update;
  41.  
  42.  
  43. //delete
  44. const deleted =  async (_, { id }) => {
  45.     return await Client.findByIdAndRemove(id);
  46. }
  47.  
  48. module.exports =  deleted;
  49.  
  50.  
  51. //display
  52. const clients= async () => {
  53.     return await Client.find({});
  54. }
  55. const client = async (_, { id }) => {
  56.     return await Client.findById(id);
  57. }
  58.  
Tags: mongo mongoose
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement