简体   繁体   中英

Mongoose - Delete property from SubDocument

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.

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 )

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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