我是新手.我正在尝试加入不同的集合来获取一些数据.我能够获得帖子创建者和喜欢的信息,但是我如何使用mongoose中的关联获得他们的评论和评论者信息的帖子?
用户架构
const userSchema = mongoose.Schema({
username: {
type: String,
minlength: [6, 'Minimum length of username must be 6 characters'],
trim: true,
lowercase: true,
required: true,
unique: true
},
email: {
type: String,
minlength: [6, 'Minimum length of email must be 6 characters'],
trim: true,
unique: true
},
password: {
type: String,
minlength: [6, 'Minimum length of password must be 6 characters'],
required: true
},
tokens: [{
access: {
type: String
},
token: {
type: String
}
}],
posts: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'post'
}]
}, {
timestamps: true
});
POST架构
const postSchema = mongoose.Schema({
title: {
type: String,
trim: true,
required: true
},
body: {
type: String,
trim: true,
required: true
},
_creator: {
type: ObjectId,
ref: 'user'
},
comments: [{
type: ObjectId,
ref: 'comment'
}],
likes: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'user'
}]
}, {
timestamps: true
});
评论架构
const commentSchema = mongoose.Schema({
title: {
type: String,
trim: true
},
_creator: {
type: ObjectId,
ref: 'user'
},
_post: {
type: ObjectId,
ref: 'post'
}
}, {
timestamps: true
});
// get posts from all users
postRoutes.get('/', authMiddleware, async(req, res) => {
try {
const user = req.user;
const posts = await Post.find({})
.populate('_creator likes comments')
.sort({
createdAt: -1
})
.limit(1);
return res.send(posts);
} catch (e) {
return res.status(400).send(e);
}
});
我只收到评论ID,但我希望评论他们的信息.我究竟做错了什么?
json_object_image
最佳答案 您正在寻找Mongoose populate
这是docs
http://mongoosejs.com/docs/populate.html的链接