Search code examples
node.jsmongodbmongoose

Using mongoose to add new field to existing document in mongodb through update method


I'm trying to update a mongodb document with mongoose in node.js

When the field exists, the update works, but if the field does not exist, the update will not work.

I want to add new fields to the document.

the MongoDB query ($set) is working:

db.getCollection('users').update({ 'uid': 'uid' }, { $set: { 'vehicle_status': 'bike' } })  

But it will not work when done in mongoose. Using $set does not add a field.

User.update({ uid: uid }, { $set: { vehicle_status: vehicleSatus } }, { multi: true })

Solution

  • Try the following code:

    User.updateOne(
         {uid: 'uid'}, 
         {vehicle_status : 'vehicleSatus' },
         {multi:true}, 
           function(err, numberAffected){  
           });
    

    Also, make sure that you add vehicle_status to the schema.