javascript - 使用带有索引变量的 $set 来更新文档

标签 javascript node.js mongodb

For the document matching the criteria _id equal to 100, the following operation update the value second element (array index of 1) in the tags field and the rating field in the first element (array index of 0) of the ratings array.

db.products.update(
   { _id: 100 },
   { $set:
      {
        "tags.1": "rain gear",
        "ratings.0.rating": 2
      }
   }
)

以上引用自mongodb $set documentation ,我将如何为索引添加一个变量,而不是 "tags.1"它变成"tags."+index

例如,如果 index等于 7 它将返回相当于 "tags.7" .

这是我的代码:

Users.findOneAndUpdate({'username': post.username}, { 
  $set: {
    "notifications.0": { 
      'id': post._id,  'message': post.message,  'amount': amount 
    } 
  } 
}, function () {})

它工作得很好,但只是因为我硬编码了 0作为索引。我想替换那个硬编码的 0index变量。

最佳答案

像这样构建查询

var key = "notifications."+index;
var obj = {};
obj[key] = { 'id': post._id, 'message': post.message, 'amount': amount };
Users.findOneAndUpdate({'username': post.username}, { $set: obj }, function () {}

关于javascript - 使用带有索引变量的 $set 来更新文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43711967/

相关文章:

javascript - 使用指定的字符集下载 BLOB 内容

javascript - 为什么我不能将 <object/> 标签插入到 CKEditor4 中?

javascript - Nodejs Paypal api

node.js - 如何在stripe中确认支付成功

javascript - 在 MongoDB 集合中查找字符串

javascript - 使用 parsley.js 验证动态创建的字段

javascript - 通过 jQuery 将来自 Firebase 的图像设置为 div 的背景

node.js - package.json 中应用程序的不同分支中的不同 Node 包版本?

node.js - 通过 Node JS 插入时,Mongo shell 不显示集合(命令 show collections)

mongodb - mongodump 忽略一些指定的集合