Javascript Mongoose以级联方式填充嵌入式文档
我正在模拟我的微博应用程序用户之间的“朋友”关系。它看起来像这样:Javascript Mongoose以级联方式填充嵌入式文档,javascript,nosql,mongoose,Javascript,Nosql,Mongoose,我正在模拟我的微博应用程序用户之间的“朋友”关系。它看起来像这样: [ { "_id": "4fd5e5f3e45fd10100000004", "birthdate": "11/11/1911", "email": "blablabla@gmail.com", "friends": [], "posts": [ { "timestamp": "2012
[
{
"_id": "4fd5e5f3e45fd10100000004",
"birthdate": "11/11/1911",
"email": "blablabla@gmail.com",
"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"
}
}
]
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);
在user.js文件中
在post.js文件中
我想要实现的是让当前用户的所有好友,以及他们的帖子和嵌入文档数组,都已经填充完毕。我笨拙地尝试了这个功能:
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);
}
});
}
});
}
我是否忽略了内部填充机制,或者应该采用不同的方法?
谢谢你如果运气好的话,我们将得到递归填充。在此之前,考虑将你想要的数据复制到帖子中(可能只有标题),并将其存储如下:
[
{
"_id": "4fd5e5f3e45fd10100000004",
"birthdate": "11/11/1911",
"email": "blablabla@gmail.com",
"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"
}
}
]
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);
然后你可以做一个常规的:
User.findOne({_id: req.params.id}).populate('friends').exec(function(err, user) { ... })