Using mongoose to add a new field to an existing document in mongodb via update method

I am trying to update a mongodb file using mongoose in node.js

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

I want to add new fields to the document.

MongoDB request ( https://docs.mongodb.com/v3.2/reference/operator/update/set/#behavior ) works:

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

But in mongoose this will not work. Using $ set does not add a field.

User.update({ uid: uid }, { $set: { vehicle_status: vehicleSatus } }, { multi: true })
+4
source share
1 answer

Try using the following code:

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

Also, make sure you add vehicle_status to the circuit.

+6
source

Source: https://habr.com/ru/post/1669218/


All Articles