Reputation: 75666
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
<% }) %>
Upvotes: 1
Views: 720
Reputation: 2699
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.
Upvotes: 1