簡體   English   中英

帶Javascript的所有MongoDB文檔中的Update字段

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

我正在嘗試為MongoDB集合中的每個文檔更新一個字段。

我從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);
  });
});

如果我在.forEach循環中進行console.log(item),則可以按期望的方式獲取集合中的每個文檔,因此到目前為止所有內容似乎都可以正常工作。

誰能看到我要去哪里錯了?

謝謝大家!

Api調用是異步的,您必須將其包裝在Promise或異步庫中才能完成構建更改。

另外,您也可以在一個調用中通過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();

為什么不像

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