I'm writing a feed reader app with express and mongoose. I have 3 schemas :
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}
});
Categories have feeds and feeds have articles.
i can populate categories with their feeds
mongoose.model("Category").find().populate("_feeds").exec(callback);
now i'd like from the Category ,to populate the feeds with their articles that have been read.
How could i do that ?
source : https://github.com/Mparaiso/FeedPress/blob/master/lib/database.js
thanks.
For one category document, that could look something like this:
// retrieve all feeds in the list and populate them
mongoose.model('Feed')
.find({ _id : { $in : category._feeds } }) // see text
.populate('_articles')
.exec(...);
(I initially thought that the array passed to $in should be a list of ObjectId's, but apparently it's okay to pass an array of documents)
EDIT: I think this works, too:
mongoose.model('Feed')
.populate(category._feeds, { path : '_articles' })
.exec(...);