Search code examples
mongodbmongoose

In mongoose, what is the difference between save(), insertOne() and updateOne(),when I want to add something new to a field that is already made?


for example I have a schema

 const  listSchema=new mongoose.Schema({
      name:String,
      items:Array
    });

const List=mongoose.model("List",listSchema);

and I made a document const list=New List({ name: "list1", items:[item1, item2,item3] });

and then later I wanted to add a new item called item 4 so I used

List.findOne({name:list1},function(err,foundList){
foundList.items.push(item4);
foundList.save();

I know it might be a stupid question but it's confusing me. When I use .push I essentially added a new item inside the array, therefore I would have 4 items inside the array now. So here comes the question: why when I used .save(), it's not adding 4 extra items but instead it only adds the item4 that I wanted to add?


Solution

  • insertOne() allows you to insert a NEW document into a collection. While save() creates a new document by calling the instance of that document, meaning the model/Object that has been created. However, If you have fetched an existing document and call .save() to it, (just like how you did in your example). it will simply updates the document with the changes you've made with it instead. Now, updateOne() basically will let you update an existing document by matched parameters.

    Examples:

    insertOne()

    let newDoc = {name:'List2',items =['item1','item2']} // creating a new object to be inserted into the collection 
    List.insertOne({newDoc},(err,result)=>{
    })
    



    updateOne()

    Let's say you have an existing document in your collection like: { name: "list1", items:[item1, item2,item3] } you can update the fields by doing:

    List.insertOne({
                     name:'list1' // meaning you are looking for a document which has a name of 'list1'
                   },
                   {
                     $push:{items:'item4'// we are using push since we know it's an array field
                     // you can also do
                     // {$set:name:'new name'} // if you want to update a string, date etc2x field
                    },(err,result)=>{
    })
    



    .save()

    You can creat a new document by doing:

    let newList = new List({
                          name:'list2'
                          items: ['item1','item2','item3'] 
                          })
    newList.save();
    

    But using it to UPDATE an EXISTING document:
    In using .save(), you may need to explicitly specify the change or which property/field you have changed. Mongoose deals nested or deep object properties differently. Here is the documentation on mongoose website: check here

    In your case, you need to do an extra step before saving, which is to specify the property/path you have modified as such:

    List.findOne({name:'list1'},
                 (err,foundList) => {
                   foundList.items.push(item4);
                   foundList.markModified('items')
                    foundList.save()
                 })