Mongoose - Delete property from SubDocument

问题: I have the following Mongoose schema and code: Schema: { ... inv: { type: Object, default: {} }, ... } Code (version 1), where tar...

问题:

I have the following Mongoose schema and code:

Schema:

{
    ...
    inv: {
        type: Object,
        default: {}
    },
    ...
}

Code (version 1), where targetData is a Mongoose Document, item is a String, and amount is a Number:

targetData.inv[item] = targetData.inv[item] - amount;
if (!targetData.inv[item]) delete targetData.inv[item];
await targetData.save();

Code (version 2):

targetData.inv[item] = targetData.inv[item] - amount;
if (!targetData.inv[item]) targetData.inv[item] = undefined;
await targetData.save();

The problem is that neither of these attempts removes targetData.inv[item] from the Document. My goal is to remove an item, say "thing", from a SubDocument. For example:

Before:

{
    ...
    inv: {
        thing: 5
    },
    ...
}

After:

{
    ...
    inv: {},
    ...
}

Note: When amount is a number less than 5 (in the above example), the code works fine. If I'm removing all 5, that's when it doesn't update, it would stay as 5.

Note 2: I'm using Mongoose 5.3.15

How can I achieve this?

EDIT: Looks like this only happens if inv only has 1 property. Having something like inv: { thing: 5, anotherThing: 6 } will work perfectly with the delete keyword.


回答1:

Found out what was wrong. All I needed to do was manually tell Mongoose that inv has been modified, using targetData.markModified("inv"). Docs. This is due to the SchemaType being Mixed (Object)


回答2:

I know that you solved the issue but I have an idea. Normally in this situation, I would like to get the document and go through the object and find the item and remove it and save the document again. It is a naive way that I'm doing.

  • 发表于 2018-12-31 22:49
  • 阅读 ( 225 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除