Mongoose如何填充引用的文档

时间:2013-07-10 15:12:07

标签: javascript node.js express mongoose

我正在用快递和猫鼬编写一个提要阅读器应用程序。 我有3个架构:

CategorySchema = new mongoose.Schema({
                title:{type:String, unqiue:true, required:true},
                created_at:{type:Date, default:Date.now},
                order:Number,
                _feeds:[
                    {type:mongoose.Schema.Types.ObjectId, ref:"Feed"}
                ]
            });

FeedSchema = new mongoose.Schema({
                xmlurl:{type:String, unique:true, required:true},
                title:{type:String, required:true},
                original_title:String,
                link:{type:String, required:true},
                favicon:String,
                date:Date,
                description:String,
                _articles:[
                    {type:mongoose.Schema.Types.ObjectId, ref:'Article'}
                ],
                _created_at:{type:Date, default:Date.now},
                _category:{type:mongoose.Schema.Types.ObjectId, ref:"Category"}

            });

ArticleSchema = new mongoose.Schema({
                title:{type:String, required:true},
                description:String,
                summary:String,
                meta:mongoose.Schema.Types.Mixed,
                link:{type:String, required:true},
                guid:String,
                categories:[String],
                tags:[String],
                pubDate:{type:Date, default:Date.now},
                _feed:{
                    type:mongoose.Schema.Types.ObjectId,
                    ref:"Feed",
                    required:true
                },
                _favorite:Boolean,
                _read:Date,
                _created_at:{type:Date, default:Date.now}
            });

类别包含Feed和Feed都有文章。

我可以使用其Feed填充类别

mongoose.model("Category").find().populate("_feeds").exec(callback);

现在我喜欢从类别中,用他们阅读的文章填充Feed。

我怎么能这样做?

来源:https://github.com/Mparaiso/FeedPress/blob/master/lib/database.js

感谢。

1 个答案:

答案 0 :(得分:0)

对于一个类别文档,可能看起来像这样:

// retrieve all feeds in the list and populate them
mongoose.model('Feed')
  .find({ _id : { $in : category._feeds } }) // see text
  .populate('_articles')
  .exec(...);

(我最初认为传递给$in的数组应该是ObjectId的列表,但显然可以传递一组文档)

编辑:我认为这也有效:

mongoose.model('Feed')
  .populate(category._feeds, { path : '_articles' })
  .exec(...);