简体   繁体   中英

using dynamic fields in mongoose

I have an Item schema and collection and a List Schema and collection.

I currently create items separately from creating lists...but each item references a list objectId.

var ListSchema = new Schema({
    name    : { type: String, required: true, trim: true }
  , user  : { type: Schema.ObjectId, ref: 'User', index: true }
  , description : { type: String, trim: true }
});


var ItemSchema = new Schema({ 
    name    : { type: String, required: true, trim: true }
  , description: { type: String, trim: true }
  , list  : { type: Schema.ObjectId, ref: 'List', index: true }
});

I want to know if it's possible to get a list and load the items for that list ontop of that instance:

So I could do:

list.items to get all the items in the view.

//routes/list.js
List.find({ user: req.params.userid }, function(err, lists){
   //i want to populate list.items here
   res.render('/lists', { lists: lists });
});

//views/list.ejs
<% lists.forEach(function(list){ %>
    List has <%= list.items.length %> items in it
<% }) %>

It looks to me like you would want to run a query for all items whose list field was equal to the list's id. Is that correct?

In that case, something like

lists.forEach(function(list){
   list.items = []
   Item.find( { list:list._id }, function(err, items) {
       items.forEach(function(item) {
           list.items.add(item);
       });
   });
});

might be what you want.

Edit

Ah, I see. How about creating a list of all of the _ids of the lists you find, then doing an $in query on the Item collection to get all the items whose list property is one of the lists you have found? This would only be one call to MongoDB to get all of the items, and you could put the res.render call inside of its callback.

Note: there would have to be some extra logic in the callback to parse the returned items and sort them by list.

Here are the docs for $in.

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