Reputation: 146
I have an array of User documents each user has followers attribute which is a number, I just want to increment this attribute by 1 and then update all those user documents in the DB at once.
In the request I have an array of user ids, I query with those ids to get an array of user documents.
const users = await User.find({"_id": {$in: req.body.ids}});
each user document has an attribute called followers which is a number.
const userSchema = new mongoose.Schema({
// other attributes...........,
followers: {
type: Number,
default: 0
}
});
I want to increment the number of followers in each user in the users array and update the DB at once without sending a request to update each user separately, Is this even possible?
Thanks in advance
Upvotes: 3
Views: 706
Reputation: 49985
You can use $inc and run updateMany
:
await User.updateMany({"_id": {$in: req.body.ids}}, { $inc: { followers: 1 } });
Upvotes: 3