我有两个模式,
一个给用户,另一个给帖子
在用户模式中,我有一个latestPost的属性,它将是post模式中条目的ObjectId
当我加载用户对象时,
我想从用户模式中获取lastestPost作为包含作者用户名的对象,其中作者是与用户模式中的_id字段匹配的ObjectId。
猫鼬教程似乎使用了
User.findOne({ _id: req.user.id})
.populate('latestPost')
.populate({ path: 'latestPost', populate: 'author'})
但这不管用
它显示
{ _id: 58f54fa51febfa307d02d356,
username: 'test',
email: 'test@test',
firstName: 'test',
lastName: 'test',
__v: 0,
latestPost:
{ _id: 58f54fa51febfa307d02d357,
user: 58f54fa51febfa307d02d356,
author: 58f54fa51febfa307d02d356,
date: 2017-04-17T23:28:37.960Z,
post: 'Test',
__v: 0 } }
但我想表现出来
latestPost:
{
author: {
username : something
}
}
如何做这样的事情?架构或查询的设计有问题吗?
var UserSchema = new Schema({
username : String,
firstName : String,
lastName : String,
email : String,
password : String,
views : Number,
latestPost : { type: Schema.Types.ObjectId, ref: 'Post' }
});
var PostSchema = new Schema({
user : { type: Schema.Types.ObjectId, ref: 'User' },
author : { type: Schema.Types.ObjectId, ref: 'User' },
date : Date,
body : String
});
var User = mongoose.model('User', UserSchema);
var Post = mongoose.model('Post', PostSchema);
User.findOne({ _id: req.user.id})
.populate('latestPost')
.populate({ path: 'latestPost', populate: 'author'})
.exec(function(err, user) {
if (err) res.json(err)
console.log(user)
})
也许只是这个。
我认为您不需要.人口('latestPost')
作为您的下一个.人口()
应该负责填充latestPost
。也许这会干扰下一个。
User.findOne({ _id: req.user.id }).populate({
path: 'latestPost',
model: 'Post',
populate: {
path: 'author',
model: 'User'
}
}).exec(function (err, user) {
});
您还需要在填充函数中提供模型名称:
var UserSchema = new Schema({
username : String,
firstName : String,
lastName : String,
email : String,
password : String,
views : Number,
latestPost : { type: Schema.Types.ObjectId, ref: 'Post' }
});
var PostSchema = new Schema({
user : { type: Schema.Types.ObjectId, ref: 'User' },
author : { type: Schema.Types.ObjectId, ref: 'User' },
date : Date,
body : String
});
var User = mongoose.model('User', UserSchema);
var Post = mongoose.model('Post', PostSchema);
User.findOne({ _id: req.user.id})
.populate('latestPost')
.populate({
model: 'Post',
path: 'latestPost',
select: 'author -_id'
})
.exec(function(err, user) {
if (err) res.json(err)
console.log(user)
})