使用 mongoose 通过 update 方法向 mongodb 中的现有文档添加新字段 [英] Using mongoose to add new field to existing document in mongodb through update method

查看:65
本文介绍了使用 mongoose 通过 update 方法向 mongodb 中的现有文档添加新字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

the MongoDB query ($set) is working:

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

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

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

推荐答案

试试下面的代码:

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

另外,请确保将 Vehicle_status 添加到架构中.

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

这篇关于使用 mongoose 通过 update 方法向 mongodb 中的现有文档添加新字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆