arrays - 将数组名称作为 mongoose 中的参数传递

标签 arrays node.js mongodb mongoose

我正在使用 mongoose,并且正在使用 findByIdAndUpdate() 函数更新我的数据库。我想将元素插入文档中存在的不同数组中。我的文档中有不同名称的不同数组。我可以将名称数组作为参数传递给该函数,还是应该创建不同的函数,其中每个函数都有不同的 nameArray

  this.findByIdAndUpdate(User._id,
                        {$push:{nameArray: 'element'}}, 
                        {upsert: true},
                        callback);

最佳答案

Node.js 4.x 中,您可以使用 computed property直接在 $push 对象文字中执行此操作的语法:

this.findByIdAndUpdate(User._id,
                       {$push: {[nameArray]: 'element'}}, 
                       {upsert: true},
                       callback);

在以前的版本中,您需要以编程方式构建 $push 对象:

var push = {};
push[nameArray] = 'element';
this.findByIdAndUpdate(User._id,
                       {$push: push}, 
                       {upsert: true},
                       callback);

关于arrays - 将数组名称作为 mongoose 中的参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25475422/

相关文章:

php - 检查 SQL 表上的数组是否有重复项

ruby - 将数组结果转换为 ruby

html - 通过 Web Audio API 使用分块音频进行断断续续/听不见的播放

node.js - 在Linux中 react 错误

node.js - NodeJS集群: how to reduce data from workers in master?

node.js - 部分文本搜索(查找)在我的 Express 应用程序上不起作用

c++ - 我如何以这种方式退出字符串数组

java - 如何将从 MongoDB 检索到的 DBObject 转换为自定义类?

mongodb - 无法访问 http ://localhost:28017 when enable auth for mongod

arrays - 使用数组作为 Map 的 'value' 部分