问题描述
我有一个用户文档数组,每个用户都有一个数字的 follower 属性,我只想将此属性加 1,然后立即更新数据库中的所有用户文档.
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.
在请求中,我有一组用户 ID,我使用这些 ID 进行查询以获取一组用户文档.
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}});
每个用户文档都有一个称为 follower 的属性,它是一个数字.
each user document has an attribute called followers which is a number.
const userSchema = new mongoose.Schema({
// other attributes...........,
followers: {
type: Number,
default: 0
}
});
我想增加 users 数组中每个用户的关注者数量并立即更新数据库,而无需发送单独更新每个用户的请求,这可能吗?
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?
提前致谢
推荐答案
您可以使用 $inc 并运行 updateMany
:
You can use $inc and run updateMany
:
await User.updateMany({"_id": {$in: req.body.ids}}, { $inc: { followers: 1 } });
这篇关于一次更新猫鼬中的多个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!