Javascript 在猫鼬中更新许多
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/54992810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Update many in mongoose
提问by Patrickkx
I have a very simple case. I want to update my collection every midnight.
Im using node-schedule:
我有一个非常简单的案例。我想每半夜更新我的收藏。我正在使用node-schedule:
schedule.scheduleJob('0 0 * * *', () => {
Users.updateMany();
});
All I want to do, is to loop over every document in my collection (Users) and then if User.createdis false, I want to turn it into true.
我想要做的就是循环遍历我的集合中的每个文档 ( Users) 然后如果User.created是false,我想把它变成true.
In javascript it would be:
在 javascript 中,它将是:
for (let user in Users) {
if (user.created === false) {
user.created = true;
}
}
How to do it in mongoose? Thanks!
如何在猫鼬中做到这一点?谢谢!
Edit: The story is very simple, I just want to iterate over every element in my db using mongoose and if iterated element has field "created" === false, change it to true.
编辑:这个故事很简单,我只想使用 mongoose 迭代我的数据库中的每个元素,如果迭代元素有字段“created” === false,请将其更改为 true。
回答by Harsh Patel
You can use updateMany()methods of mongodb to update multiple document
可以使用updateMany()mongodb的方法更新多个文档
Simple query is like this
简单的查询是这样的
db.collection.updateMany(filter, update, options)
For more doc of uppdateMany read here
有关 updateMany 的更多文档,请阅读此处
As per your requirementthe update codewill be like this:
根据您的要求,更新代码将如下所示:
User.updateMany({"created": false}, {"$set":{"created": true}});
here you need to use $setbecause you just want to change created from true to false. For ref. If you want to change entire doc then you don't need to use $set
在这里您需要使用$set因为您只想将 created 从 true 更改为 false。对于参考。如果您想更改整个文档,则不需要使用$set
回答by jakedipity
You first need a query to find the documents you want to update. This is simply:
您首先需要查询以查找要更新的文档。这很简单:
{"created": false}
Then you need an update query to tell mongo how to update those documents:
然后你需要一个更新查询来告诉 mongo 如何更新这些文档:
{"$set":{"created": true}}
You need to use the $setoperator 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:
您需要使用$set运算符来指定要更改哪些字段,否则会覆盖整个文档。最后,您可以将这些组件组合到一个带有附加参数的 mongo 调用中,以告诉 mongo 我们要修改多个文档:
User.update({"created": false}, {"$set":{"created": true}}, {"multi": true}, (err, writeResult) => {});
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/
Mongoose 尝试密切复制 mongo API,因此所有这些信息都可以仅在 MongoDB 的文档中找到:https: //docs.mongodb.com/manual/reference/method/db.collection.update/

