【问题标题】:How to allow null field when updating in Mongoose?在 Mongoose 中更新时如何允许空字段?
【发布时间】:2012-11-29 06:05:13
【问题描述】:
Venue.update({_id : venue.id},                         
    {
      name : venue.name,
      'contact.phone' : venue.contact.formattedPhone                      
    }, {upsert: true}).exec()

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

编辑:

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

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

【问题讨论】:

  • 您使用的是null。如果是这样,请改用undefined。我想这个线程可能会帮助stackoverflow.com/questions/12636938/…
  • 我们可以做类似'if formattedPhone == undefined than contact.phone is ''的事情吗?
  • 其实我是 Django 人,目前正在过渡到 node.js。我对 mongoengine 很有经验。我还不太了解猫鼬。我猜你也是一个切换到 Node 的 Django 人 :)
  • 完全正确:) 我刚搬到 Node.js 和 Mongoose
  • 我不明白你在寻找什么行为。能举个具体的例子吗?

标签: node.js mongodb mongoose


【解决方案1】:

以编程方式构建您的 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();

【讨论】:

    猜你喜欢
    • 2020-02-07
    • 2021-06-21
    • 2019-09-10
    • 1970-01-01
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    相关资源
    最近更新 更多