【发布时间】:2021-11-27 00:16:43
【问题描述】:
我是 NoSQL 的新手,在本例中是 MongoDB。我正在尝试使用ExpressJS 和Mongoose 制作API。有一些数据模型
User.js
const UserSchema = new mongoose.Schema(
{
username: {
type: String,
required: true,
min: 3,
max: 50,
unique: true,
},
email: {
type: String,
required: true,
max: 50,
unique: true,
},
password: {
type: String,
required: true,
min: 6,
},
profilePicture: {
type: Schema.Types.ObjectId,
ref: "Image",
},
}
Image.js
const ImageSchema = new mongoose.Schema(
{
desc: {
type: String,
},
url: {
type: String,
},
},
{ timestamps: true }
)
Post.js
const PostSchema = new mongoose.Schema(
{
username: {
type: String,
required: true,
},
title: {
type: String,
required: true,
},
desc: {
type: String,
max: 300,
required: true,
},
images: [
{
type: Schema.Types.ObjectId,
ref: "Image",
},
],
comments: [
{
type: Schema.Types.ObjectId,
ref: "Comment",
},
],
}
)
Comment.js
const CommentSchema = new mongoose.Schema(
{
user: {
type: Schema.Types.ObjectId,
ref: "User",
},
text: {
type: String,
required: true,
trim: true,
},
}
现在我想执行一个查询,根据特定的postId 获取所有 cmets。并且响应数据必须包括User数据和image url与User相关的数据。我试过这个来获取评论数据
const comments = await Comment.find({post: req.params.postId}).populate("user")
它返回 Comment 和 User 数据,但不包括 Image。如何执行该查询?
【问题讨论】: