javascript - 使用 Mongoose 进行动态查询

标签 javascript node.js mongodb mongoose database

我正在尝试使用 Mongoose 创建动态条件,但它并不像我想象的那样工作。

代码是这样的

id = req.params.questionId;
index = req.params.index;

callback = function(err,value){
   if(err){

       res.send(err)

   }else{

       res.send(value)

    }
};

conditions = {
    "_id": id,
    "array._id": filterId
};
updates = {
   $push: {
      "array.$.array2."+index+".answeredBy": userId
   }
};
options = {
  upsert: true
};

Model.update(conditions, updates, options, callback);

如您所见,我正在尝试使用“index”变量创建动态条件。可以这样做吗?

提前谢谢您!

最佳答案

您需要分两步创建 updates 对象:

var updates = { $push: {} };
updates.$push["array.$.array2." + index + ".answeredBy"] = userId;

更新

现在node.js 4+支持computed property names ,您可以一步完成此操作:

var updates = { $push: {
    ["array.$.array2." + index + ".answeredBy"]: userId
} };

关于javascript - 使用 Mongoose 进行动态查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23582133/

相关文章:

大型文档的 mongodb 性能

javascript - 表行中不支持顶级属性

javascript - ReactJS 用于编辑评论

javascript - 如何查找所有行并获取 sequelize 中所有行的总金额

在 MacOs High Sierra 中运行的 MongoDB 写入操作非常慢

javascript - Meteor react 收集数据

javascript - 获取列表项在无序列表中的位置(即第三个列表项是 3)

javascript - 带有动态图像 block 的 Shopify 光滑轮播

node.js - Node Redis : How to filter a sorted set of keys and retrieve each keys hashed values in one call

node.js - 使用 PhantomJS 处理多个用户对多个远程 Web 表单的请求