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
<% }) %>
这会工作,我想知道是否有更多的mongo-ish方式来做到这一点。或者创建一个List.methods.items函数为我执行此操作。 – chovy
作者mongo-ish,你的意思是在List集合中的同一个查询中吗?既然你想从两个独立的集合中获取数据,你将需要执行两个查询。 – shelman
这不起作用,因为我需要填充list.items后调用res.render()。 Item.find()在一个循环中,这是我必须要做的。 – chovy