Search code examples
javascriptnode.jsmongodbmongoosesubdocument

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.


Solution

  • 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)