简体   繁体   中英

Query nested object dynamically in Mongodb + Mongoose.js

How might I perform this query in Mongoose.js + MongoDB?

I have a simple schema where ratings are stored by user id, to avoid duplication. For reading and writing to given objects this works fine. But how might I query MongoDB for all items where a particular viewer has rated it?

For instance, this works fine in the MongoDB shell:

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

But I'd like to query this programmatically in Node.js + Mongoose.js like so,

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

Where i'm getting stumped is Mongoose.js takes the dot notation for inner objects, but that interprets user_id as a literal, and Mongoose.js doesn't take square bracket notation for inner objects.

Here's an example schema;

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

And an example of such data:

[ { 
      name: "Toaster", 
      ratings: {
          "52126672b9f5bd670b000001": 1,
          "52155b39a411791c29000001": -1
      }
   }, 
   { 
      name: "Griddle", 
      ratings: {
          "52126672b9f5bd670b000001": 1,
          "52126672b9f5bd670b000001": 1"
      }
   }
}
var user_id = req.params.id;
var query = {};
query['ratings.' + user_id] = {$exists: true};
Item.find(query, function(err, items) { ... });

The key in the object you send to Item.find have to be a string. To construct a string of any arbitrary values you have to first create the object and then use the bracket notation to define it (that is: query[anything+here] = data ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM