问题描述
我有一个非常简单的案例.我想在每个午夜更新我的收藏.我正在使用node-schedule
:
I have a very simple case. I want to update my collection every midnight.Im using node-schedule
:
schedule.scheduleJob('0 0 * * *', () => {
Users.updateMany();
});
我要做的就是遍历集合(Users
)中的每个文档,然后如果User.created
是false
,我想将其转换为true
.
All I want to do, is to loop over every document in my collection (Users
) and then if User.created
is false
, I want to turn it into true
.
在javascript中,应该是:
In javascript it would be:
for (let user in Users) {
if (user.created === false) {
user.created = true;
}
}
如何用猫鼬做这件事?谢谢!
How to do it in mongoose? Thanks!
推荐答案
您首先需要查询以查找要更新的文档.这很简单:
You first need a query to find the documents you want to update. This is simply:
{"created": false}
然后,您需要一个更新查询来告诉mongo如何更新那些文档:
Then you need an update query to tell mongo how to update those documents:
{"$set":{"created": true}}
您需要使用$set
运算符来指定要更改的字段,否则它将覆盖整个文档.最后,您可以将这些组件与一个带有附加参数的单个mongo调用组合在一起,以告诉mongo我们要修改多个文档:
You need to use the $set
operator to specify which fields to change, otherwise it will overwrite the entire document. Finally you can combine these components into a single mongo call with an additional parameter to tell mongo we want to modify multiple documents:
User.update({"created": false}, {"$set":{"created": true}}, {"multi": true}, (err, writeResult) => {});
Mongoose尝试紧密复制mongo API,以便仅在MongoDB的文档中可以找到所有这些信息: https://docs.mongodb.com/manual/reference/method/db.collection.update/
Mongoose tries to closely replicate the mongo API so all this information can be found solely within MongoDB's documentation: https://docs.mongodb.com/manual/reference/method/db.collection.update/
这篇关于更新许多猫鼬的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!