2012-10-03 72 views
0

我有一个项目模式和集合以及一个列表模式和集合。在猫鼬中使用动态字段

我目前创建项目与创建列表分开......但每个项目都引用一个列表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 } 
}); 

我想知道是否有可能得到一个列表,并加载项该列表ontop的该实例:

所以,我可以这样做:

list.items得到中的所有项目风景。

//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 
<% }) %> 

回答

1

它在我看来像你想运行一个查询的所有项目的list字段等于列表的ID。那是对的吗?

在这种情况下,像

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

可能是你想要什么。

编辑

啊,我明白了。如何创建列表中的所有_id列表,然后在Item集合上执行$ in查询以获取list属性是您找到的列表之一的所有项目?这只会是一次调用MongoDB来获取所有项目,并且您可以将res.render调用放入其回调函数中。

注意:在回调中必须有一些额外的逻辑来解析返回的项目并按列表对它们进行排序。

这里是docs为$ in。

+0

这会工作,我想知道是否有更多的mongo-ish方式来做到这一点。或者创建一个List.methods.items函数为我执行此操作。 – chovy

+0

作者mongo-ish,你的意思是在List集合中的同一个查询中吗?既然你想从两个独立的集合中获取数据,你将需要执行两个查询。 – shelman

+0

这不起作用,因为我需要填充list.items后调用res.render()。 Item.find()在一个循环中,这是我必须要做的。 – chovy