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

余生长醉 提交于 2021-02-07 05:27:11

问题


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 })

回答1:


Try the following code:

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

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




回答2:


Going through this solution in Year 2019.

Please note: collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead




回答3:


According to new scenario always use {upsert:true}.

upsert - if set to true and no record matched to the query, replacement object is inserted as a new record.

   user.updateOne(
                 { email: req.body.email },
                 { $set: { name: 'Aaakash'}},{upsert:true}).then((result, err) => {
                    return res.status(200).json({ data: result, message:"Value Updated" });
                })


来源:https://stackoverflow.com/questions/42127373/using-mongoose-to-add-new-field-to-existing-document-in-mongodb-through-update-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!