1

Item スキーマとコレクション、および 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 }
});

リストを取得して、そのリストのアイテムをそのインスタンスの上にロードできるかどうかを知りたいです。

だから私はできる:

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

1 に答える 1

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見つけたリストの 1 つにプロパティが含まれるすべてのアイテムを取得するのはどうでしょうか? res.renderこれは、すべての項目を取得するために MongoDB を 1 回呼び出すだけで済み、呼び出しをそのコールバック内に置くことができます。

注: 返された項目を解析してリストで並べ替えるには、コールバックに追加のロジックが必要です。

$inのドキュメントは次のとおりです。

于 2012-10-03T21:12:08.070 に答える