我试图仅显示会话用户订阅的用户的文档(使用mongoose在mongo中)。订阅的用户被添加到用户文档内的“跟随”数组中。用户只能看到该数组中的对象(帖子)。
我正在使用node express。这是使用mongoose的populate方法的尝试。
var user = req.user;
var posts = [];
Post.populate(posts, {path: "post.creator", match: {'creator': user.following}}, function (err, posts) {
if (err) {
return next(err);
}
posts.forEach(function (post) {
posts.push(post);
});
console.log(posts);
return res.render('subscribed', {posts: posts, user: user});
});
我是mongoose的新手,并且直到现在才提取批量文档而没有任何疑问。
用户模型如下:
//required stuff and set up
...
//user object
var UserSchema = Schema({
username: {
type: String,
},
posts: [{
type: Schema.Types.ObjectId,
ref: 'Post'
}],
following: [{
type: Schema.Types.ObjectId,
ref: 'User'
}],
followers: [{
type: Schema.Types.ObjectId,
ref: 'User'
}],
)}
//exports etc
...
帖子架构
//required stuff and set up
...
//post object
var PostSchema = Schema({
title: {
type: String,
required: true,
trim: true
},
createdAt: {
type: Date,
default: Date.now
},
creator: {
type: Schema.Types.ObjectId,
ref: 'User'
}
});
//exports etc
...
非常感谢任何帮助。