猫鼬Document.set无法保存到实际的数据库

时间:2020-05-27 17:11:44

标签: javascript node.js mongodb mongoose

我正在使用JSON数组在Collection上进行手动更新。

我遍历数组,然后首先找到一个匹配项。如果存在匹配项,则在其上调用set-否则,将其insert放入collection

for (let obj of objs) {
    //check for match where 'foo' and 'bar' Objects match
    const match = await Model.findOne({foo:obj.foo, bar:obj.bar});

    if (match) {
        //show value b4 update
        console.log('b4 ', match.fizz);

        //If match, then update the 'fizz' field 
        match.set({fizz:obj.fizz});

        //This actually shows that the update happened
        console.log('after ', match.fizz);
    } else {
      //Otherwise, insert this new Object into the Collection
      await Model.insert(obj)
    }
 }

问题是当我进入Mongo时,实际数据库中的记录没有得到更新。但是,我的调试表明它已经更新,使我相信set命令“有效”。奇怪的是insert似乎可以正常工作,而且我在数据库中看到了新文档,而不是更新的文档。关于会发生什么的任何想法?谢谢

2 个答案:

答案 0 :(得分:1)

执行set语句比执行save语句

答案 1 :(得分:1)

document.set()并不意味着将文档保存到数据库。您可以使用document.set()来修改本地文档,如果要将修改保存到数据库中,请使用document.save()

match.set({ fizz: obj.fizz });
await match.save();

提示: 如果您的obj仅包含foobarfizz,并且您想更新fizz

,则可以使用以下内容来添加文档
await Model.findOneAndUpdate(
  { foo: obj.foo, bar: obj.bar }, 
  { $set: { fizz: obj.fizz } },
  { upsert: true }
)