我在MongoDB数据库中有两个集合,Post和User。每个帖子都包含创建者的ObjectId。当从数据库中获取所有帖子时,我想添加名称信息,这是User/creater的一个字段。我试图通过post.creator.name访问名称字段,但它不起作用。
const postSchema = new Schema(
{
title: {
type: String,
required: true,
},
category: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
imageUrl: {
type: String,
required: true,
},
creator: {
type: Schema.Types.ObjectId,
ref: "User",
required: true,
},
},
{ timestamps: true }
);
const userSchema = new Schema({
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
name: {
type: String,
required: true,
},
status: {
type: String,
required: true,
},
isExpert: {
type: Boolean,
required: true,
},
posts: [
{
type: Schema.Types.ObjectId,
ref: "Post",
},
],
});
exports.getPosts = (req, res, next) => {
Post.find({}).then((posts) => {
const postsWithAuthorName = posts.map(post => {
return {
...post,
name: post.creator.name
}
})
res.status(200).json({
posts: postsWithAuthorName,
});
});
};
试试这个
Post.find({}).populate('creator', 'name')
请参阅填充文档以供参考。
当你查询帖子时,创建者只是一个ObjectId
,所以你不能只调用它上的.name
。要使其工作,你需要使用例如populate
来查找这些数据。