简体   繁体   English

带Javascript的所有MongoDB文档中的Update字段

[英]Update Field in all MongoDB Documents w/ Javascript

I'm trying to update a field for every Document in a MongoDB collection. 我正在尝试为MongoDB集合中的每个文档更新一个字段。

I added the field from the Mongo shell, but I want to change each fields' value to a random number. 我从Mongo shell中添加了该字段,但是我想将每个字段的值更改为一个随机数。

User.find({}, function(err, items){
  if (err){
    consele.log('err');
    consele.log(err);
  }
  items.forEach(function(item){
    var time = (Math.floor(Math.random() * (1474893715201 - 1474800000000) + 1474800000000));
    item.update({}, {$set:{"lastLogin": time}}, false, true);
  });
});

If I console.log(item) in the .forEach loop, I get each document in the collection as I'd expect, so everything up to there seems to be working. 如果我在.forEach循环中进行console.log(item),则可以按期望的方式获取集合中的每个文档,因此到目前为止所有内容似乎都可以正常工作。

Can anyone see where I'm going wrong? 谁能看到我要去哪里错了?

Thanks peoples! 谢谢大家!

The Api calls are asynchronous, your going to have to wrap this in a promise, or async library to get the build changes done. Api调用是异步的,您必须将其包装在Promise或异步库中才能完成构建更改。

Alternatively you can also do a bulk find and update through mongo in one call: https://docs.mongodb.com/manual/reference/method/Bulk.find.update/ 另外,您也可以在一个调用中通过mongo进行批量查找和更新: https//docs.mongodb.com/manual/reference/method/Bulk.find.update/

var bulk = db.items.initializeUnorderedBulkOp();
bulk.find( { status: "D" } ).update( { $set: { status: "I", points: "0" } } );
bulk.find( { item: null } ).update( { $set: { item: "TBD" } } );
bulk.execute();

why not something like 为什么不像

User.find({}, function(err, items){
  if (err){
    consele.log('err');
    consele.log(err);
  }
  items.forEach(function(item){
    var time = (Math.floor(Math.random() * (1474893715201 - 1474800000000) + 1474800000000));
    item.lastLogin = time;
    User.save(item); // or item.save() based on driver you are using 
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM