【问题标题】:Query nested object dynamically in Mongodb + Mongoose.js在 Mongodb + Mongoose.js 中动态查询嵌套对象
【发布时间】:2013-09-12 04:36:05
【问题描述】:

如何在 Mongoose.js + MongoDB 中执行此查询?

我有一个简单的架构,其中评级按用户 ID 存储,以避免重复。对于给定对象的读写,这很好用。但是,我如何查询 MongoDB 以获取特定查看者对其进行评分的所有项目?

例如,这在 MongoDB shell 中运行良好:

db.items.find({ratings.52126672b9f5bd670b000001: {$exists: true}})

但我想像这样在 Node.js + Mongoose.js 中以编程方式查询这个,

var user_id = req.params.id;
Item.find({ ratings.user_id : {$exists: true}}, function(err, items) { ... });

我被难住的地方是 Mongoose.js 对内部对象采用点表示法,但这会将 user_id 解释为文字,而 Mongoose.js 不对内部对象采用方括号表示法。

这是一个示例架构;

var ItemSchema = new mongoose.Schema({
   name:  { type: String, required: true },
   ratings: { type: mongoose.Schema.Types.Mixed} 
});

以及此类数据的示例:

[ { 
      name: "Toaster", 
      ratings: {
          "52126672b9f5bd670b000001": 1,
          "52155b39a411791c29000001": -1
      }
   }, 
   { 
      name: "Griddle", 
      ratings: {
          "52126672b9f5bd670b000001": 1,
          "52126672b9f5bd670b000001": 1"
      }
   }
}

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:
    var user_id = req.params.id;
    var query = {};
    query['ratings.' + user_id] = {$exists: true};
    Item.find(query, function(err, items) { ... });
    

    您发送到 Item.find 的对象中的键必须是字符串。要构造任意值的字符串,您必须首先创建对象,然后使用括号表示法来定义它(即:query[anything+here] = data)。

    【讨论】:

      猜你喜欢
      • 2021-01-24
      • 1970-01-01
      • 2017-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-23
      • 1970-01-01
      • 2018-11-01
      相关资源
      最近更新 更多