【问题标题】:Do not update field if document already exists (but always update the other fields)如果文档已存在,则不要更新字段(但始终更新其他字段)
【发布时间】:2017-08-24 03:50:10
【问题描述】:

我有一个使用 Mongoose 的更新语句,如下所示:

Model.update(condition, {
   foo: '1',
   bar: '2',
   baz: '3'
}, 
{

 new: true,
 upsert: true

}, function(err, result){

});

这是我的难题 - 如果不存在任何文档,我只想设置 bar 字段。但总是想设置 foo 和 baz 字段,不管。

有没有办法通过一个查询来做到这一点,还是我必须使用多个查询来做到这一点?

【问题讨论】:

标签: node.js mongodb mongoose


【解决方案1】:

应该可以正常工作

condition = {}
// want to include bar with $and condition 
condition.bar = '2'
Model.findOneAndUpdate(condition, 
{
  $set:{
    foo: '1',
    baz: '3'
  }
},
{

 new: true,
 upsert: true

}, function(err, result){

});

【讨论】:

    猜你喜欢
    • 2021-04-24
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 2016-08-25
    相关资源
    最近更新 更多