Roman Roman
Roman Roman

Reputation: 917

How to pull array of documents from array of documents?

I have a document like this

{
    users: [
        {
            name: 'John',
            id: 1
        },
        {
            name: 'Mark',
            id: 2
        },
        {
            name: 'Mike',
            id: 3
        },
        {
            name: 'Anna',
            id: 4
        }
    ]
}

and I want to remove users from the array with ids 2 and 4. To do that I execute the following code:

const documents = [
    {
        id: 2
    },
    {
        id: 4
    },
]
Model.updateOne({ document_id: 1 }, { $pull: { users: { $in: documents } } });

But it doesn't remove any user.

Could you say me what I'm doing wrong and how to achieve the needed result?

Upvotes: 0

Views: 25

Answers (1)

dnickless
dnickless

Reputation: 10918

This works if you can redefine the structure of your documents array:

const documents = [2, 4]
Model.updateOne({ document_id: 1 }, { $pull: { users: { id: { $in: documents } } } })

Upvotes: 2

Related Questions