简体   繁体   English

ZCCADCDEDB567ABAE643E15DCF0974E503Z findOneAndUpdate 未定义设置为 null

[英]Mongoose findOneAndUpdate with undefined set as null

I have problem understanding findOneAndUpdate with undefined and null.我在理解 findOneAndUpdate 和未定义和 null 时遇到问题。

when creating an object:创建 object 时:

const user = new User({
   _id: 1,
   name: "foo",
   address: undefined
});
user.save()

It's creating a new document with only name and no address:它正在创建一个只有名称而没有地址的新文档:

{
   name: "foo"
}

If I'm using the same logic with findOneAndUpdate after:如果我在 findOneAndUpdate 之后使用相同的逻辑:

findOneAndUpdate({_id: 1}, {
   name: "bar",
   address: undefined
});

the document in the database will now contain a null for address:数据库中的文档现在将包含一个null的地址:

{
   name: "bar",
   address: null,
}

Which I can't understand why.我不明白为什么。

I would expect that when I set a value to undefined it should remove the current item, So if I had for example a document with address: "somewhere" , or even without address at all, I expect that setting undefined should remove it (or not set if wasn't there), instead of set it to null.我希望当我将一个值设置为undefined时,它应该删除当前项目,因此,如果我有一个带有address: "somewhere" ,甚至根本没有address ,我希望设置undefined应该删除它(或如果不存在则不设置),而不是将其设置为 null。

Is this something I can achieve somehow?这是我能以某种方式实现的吗? or is this the behavior of findOneAndUpdate?或者这是 findOneAndUpdate 的行为? mongodb? mongodb? (or mongoose?) (或 mongoose?)

Thanks in advance, Etay.在此先感谢,Etay。

Yeah, this is because the method findOneAndUpdate have an attribute option that can´t avoid the undefined variables from an object and set a null value by default.是的,这是因为findOneAndUpdate方法有一个属性选项,它无法避免 object 中的未定义变量,并默认设置 null 值。 To fix this, you only pass the option "omitUndefined: true" because by default is false.要解决此问题,您只需传递选项"omitUndefined: true" ,因为默认情况下为 false。 An example of code to apply:要应用的代码示例:

    await this.yourModel.findByIdAndUpdate(
            object._id,
            object,
            {
              new: true,
              omitUndefined: true
            },
          )

This solution is only available with Mongoose.此解决方案仅适用于 Mongoose。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM