问题描述
我有两个模式
一个用于用户,另一个用于发布
one for user and another one for post
在用户架构中,我具有了latestPost的属性,该属性将是帖子架构中条目的ObjectId
in the user schema, I've got a property for latestPost which would be an ObjectId of an entry in the post schema
当我加载用户对象时,
我想从用户架构中获取lastest作为包含作者用户名的对象,其中作者是与用户架构中_id字段匹配的ObjectId.
I want to get the lastestPost as an object that includes the author's username from the user schema where the author is an ObjectId that'd match an _id field in the user schema.
猫鼬教程似乎使用的语法
the mongoose tutorials seem to use the syntax of
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
}
}
一个人怎么做这样的事情?模式或查询的设计有问题吗?
how does one do something like this? is there something wrong with the design of the schema or the query?
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)
})
推荐答案
也许就是这个.
我认为您不需要.populate('latestPost')
,因为下一个.populate()
应该照顾到latestPost
的填充.也许这正在干扰下一个.
I don't think you need .populate('latestPost')
as your next .populate()
should take care of populating the latestPost
. Maybe that is interfering with the next one.
User.findOne({ _id: req.user.id }).populate({
path: 'latestPost',
model: 'Post',
populate: {
path: 'author',
model: 'User'
}
}).exec(function (err, user) {
});
这篇关于猫鼬深居的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!