【问题标题】:using dynamic fields in mongoose在猫鼬中使用动态字段
【发布时间】:2012-09-24 20:07:07
【问题描述】:

我有一个项目架构和集合以及一个列表架构和集合。

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

我想知道是否可以获取一个列表并将该列表的项目加载到该实例的顶部:

所以我可以这样做:

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

【问题讨论】:

    标签: node.js mongodb express mongoose ejs


    【解决方案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 调用放在其回调中。

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

    这里是 $in 的 docs

    【讨论】:

    • 这行得通,我想知道是否有更多的mongo-ish方式来做到这一点。或者为我创建一个 List.methods.items 函数。
    • mongo-ish,你的意思是在 List 集合的同一个查询中吗?由于您想从两个单独的集合中获取数据,因此您需要执行两个查询。
    • 这行不通,因为我需要在填充 list.items 后调用 res.render()。 Item.find() 处于一个循环中,这是我必须这样做的地方..
    猜你喜欢
    • 2018-12-12
    • 2020-10-15
    • 2014-06-10
    • 2019-11-20
    • 2016-07-21
    • 1970-01-01
    • 2014-08-22
    • 2017-10-05
    • 1970-01-01
    相关资源
    最近更新 更多