Ben
Ben

Reputation: 16659

Updating multiple documents based on condition

My Express API has two main entities:

Each user has a list of clientIds they are allowed to see.

When a new client is added to the system, that clientId needs to be added to all users who are allowed to see newly added clients.

How would I do the update query in Mongoose, considering that I need to add the new clientId to the existing list of clientIds for each user who has canSeeNewClients == true?

User.updateMany(
    // Find all users who can see new clients
    {"canSeeNewClients": true},
    // Add the new clientId to the user's list of clientIds 
    {"$set":{"listOfClientIds": ??? }}
);

Upvotes: 1

Views: 37

Answers (1)

Ayoub
Ayoub

Reputation: 1435

Assuming that your User model look somthing like this:

{
    "_id": "123",
    "canSeeNewClients": true,
    "clientIds": [
        "2",
        "3"
    ]
}

then you can add the clientId with an update and $push, you can replace $push with $addToSet to be sure that a clientId won't be added twice:

await Users.updateMany(
    { canSeeNewClients: true },
    { $push: { clientIds: clientId } }
);

Upvotes: 2

Related Questions