Reputation: 685
I am modeling a 'friends' relationship between the user of my micro-blog app. It looks something like this:
in the user.js file
var db = require('mongoose')
, Schema = db.Schema
, ObjectId=Schema.ObjectId;
var userSchema = new Schema({
name:{firstname:String,surname:String},
birthdate:String,
email:String,
posts: [new Schema({
timestamp:Date,
post:{type: ObjectId, ref: 'Post'}
})],
friends: [new Schema({
friend: {type:ObjectId, ref:'User'}
})]
});
module.exports = db.model('User', userSchema);
in the post.js file
var db = require('mongoose')
, Schema = db.Schema,
ObjectId=Schema.ObjectId;
var postSchema = new Schema({
title:String,
content:String,
});
module.exports = db.model('Post', eventSchema);
What I want to achieve is to get all the current user's friends, with their posts array of embedded document, already populated. I clumsily tried with this function:
function getUserFriendsPost(req, res) {
var count = 0;
var output = new Array();
User.findOne({
_id: req.params.id
}, function(err, user) {
for (var i = 0; i < user.friends.length; i++) {
User.findOne({
_id: user.friends[i].friend
}).populate('posts.post').exec(function(err, post) {
output.push(post);
count++;
if (count==user.friends.length) {
res.send(output);
}
});
}
});
}
What I get instead is the friends array correctly returned but the element of the posts having value of null, like this:
[
{
"_id": "4fd5e5f3e45fd10100000004",
"birthdate": "11/11/1911",
"email": "[email protected]",
"friends": [],
"posts": [
{
"timestamp": "2012-04-12T16:47:14.576Z",
"post": null,
"_id": "4f870712c488cf0100000081"
},
{
"timestamp": "2012-04-12T16:48:42.282Z",
"post": null,
"_id": "4f87076ac488cf01000000a3"
},
{
"timestamp": "2012-04-12T16:56:26.062Z",
"post": null,
"_id": "4f87093ac488cf0100000117"
}
"name": {
"firstname": "John",
"surname": "Doe"
}
}
]
Is there something that I am overlooking the in populate mechanism or should I proceed with a different approach? Thank you
Upvotes: 1
Views: 3093
Reputation: 1721
With any luck we will get recursive populating in Mongoose 3.0. Until then consider duplicating the data you want from the post (likely only the title) and storing it like this:
var db = require('mongoose')
, Schema = db.Schema
, ObjectId = Schema.ObjectId;
var userSchema = new Schema({
name: {firstname: String, surname: String},
birthdate: String,
email: String,
posts: [new Schema({
timestamp: Date,
title: String,
post: {type: ObjectId, ref: 'Post'}
})],
friends: [new Schema({
friend: {type: ObjectId, ref: 'User'}
})]
});
module.exports = db.model('User', userSchema);
Then you can do a regular:
User.findOne({_id: req.params.id}).populate('friends').exec(function(err, user) { ... })
Upvotes: 2