如果字段不在新文档中,则更新插入会删除该字段

Upsert removes field if it's not in the new document

本文关键字:字段 更新 插入 删除 新文档 文档 如果      更新时间:2023-09-26

让我们假设以下模型(注strict:false):

var Test = db.model('Test', {
  a: {type: String, required: true},
  b: {type: String}
}, {strict: false});

我目前在数据库中有这个文档:

{
  'a': 'hello',
  'b': 'world',
  'c': {
       'x': 'embedded',
       'z': 'document' 
     }
}

如果我upsert以下文档:

doc = {
  'a': 'hello',
  'b': 'jack'
}

像这样:

Test.findOneAndUpdate({
  a: 'hello'
}, doc, {upsert:true}, function(){});

我最终会得到:

{
  'a': 'hello',
  'b': 'jack'
}

换句话说,将擦除更新插入文档中不存在的字段c

如何在不擦除此类字段的情况下安全地更新插入?

奇怪,这应该按原样工作。也许您可以尝试显式设置字段:

doc = {$set: {
  'a': 'hello',
  'b': 'jack'
}};