node.js - Mongoose 更新时如何允许空字段?

标签 node.js mongodb mongoose

Venue.update({_id : venue.id},                         
    {
      name : venue.name,
      'contact.phone' : venue.contact.formattedPhone                      
    }, {upsert: true}).exec()

在此代码中,如果 field 没有电话,则不会执行更新插入操作。我怎样才能避免这种情况?如果该字段不为空,我想更新该字段,但如果为空,则不包含该字段。

编辑:

 Venue.update({_id : venue.id}, 
{
    name : venue.name,
    'contact.phone' : ((!venue.contact.formattedPhone)? 
                      '' : venue.contact.formattedPhone)                           
}, {upsert: true, safe:false}).exec()

这段代码工作正常,但这次,“电话”字段是“”。我想要的是,如果未定义字段,则隐藏该字段。

最佳答案

以编程方式构建您的 update 对象,以便在未提供时不包含 'contact.phone':

var update = {
    name : venue.name
};
if (venue.contact.formattedPhone) {
    update['contact.phone'] = venue.contact.formattedPhone;
}
Venue.update({_id : venue.id}, update, {upsert: true, safe:false}).exec();

关于node.js - Mongoose 更新时如何允许空字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13824452/

相关文章:

javascript - 在 typescript 中使用 Mongoose 填充查询

node.js - NodeJS、Mongoose - 插入数据时出现重复条目

node.js - 无法测试 mongo 聚合 MongoError : Unrecognized pipeline stage name: '$set'

javascript - 回调不是 mongoose.find({}) 中的函数

python - mongodump 然后删除 : Not exact same number of records

node.js - 类名jade中的变量

node.js - Google 翻译 api 响应不是目标语言

node.js - React 不会切换到生产模式

javascript - Put Request、JQuery、MongoDB 和 Mongoose 的更新问题

javascript - 为什么我们不能将 'console' 视为 'global' 对象的属性?