我知道这个问题之前已经提出过很多次,而且 Mongo 没有那个确切的“有很多”联系,但到目前为止我未能在两个模式之间建立联系。这是我所拥有的:
用户模型(user.js)
var userSchema = mongoose.Schema({
posts: {
_id : { type: Schema.Types.ObjectId, ref: 'Post' },
title : {type: String, ref: 'Post'}
},
facebook : {
id : String,
token : String,
email : String,
name : String
}
});
并发布架构(post.js)
var meetingsSchema = mongoose.Schema({
title: String,
description: String,
_owner: { type: Schema.Types.ObjectId, ref: 'User' },
ownerName: { type: String, ref: 'User' },
created_at: { type: Date, default: Date.now },
});
我使用模式人口,它与 post 完美配合:他们每个人都有所有者。但是,它不适用于用户。我希望能够检索显示属于他们的帖子的用户列表。在 routes.js 我定义了一个对数据库的 api 调用
app.get('/api/users', function(req, res) {
User.find(function(err, users) {
if (err)
res.send(err)
res.json(users);
}).populate('posts._id', 'posts.title');
});
但是,在 shell 和客户端 user.posts 上(毫不奇怪)都返回空数组。如何正确绑定这两个模型?