node.js 使用 mongoose 通过 update 方法向 mongodb 中的现有文档添加新字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42127373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:59:02  来源:igfitidea点击:

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

node.jsmongodbmongoose

提问by sabper

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

我正在尝试在 node.js 中使用 mongoose 更新 mongodb 文档

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:

MongoDB 查询 ( $set) 正在工作:

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.

但是在猫鼬中完成时它不起作用。使用 $set 不会添加字段。

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

回答by Tim Baker

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.

此外,请确保将 vehicle_status 添加到架构中。

回答by Shu.T

Going through this solution in Year 2019.

在 2019 年通过此解决方案。

Please note: collection.updateis deprecated. Use updateOne, updateMany, or bulkWriteinstead

请注意:collection.update已弃用。使用updateOne, updateMany, 或bulkWrite代替

回答by nagender pratap chauhan

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

根据新场景,始终使用 { upsert:true}。

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

upsert - 如果设置为 true 并且没有与查询匹配的记录,则替换对象将作为新记录插入。

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