我是 NoSQL 的新手,在這種情況下是 MongoDB。我正在嘗試使用ExpressJS和制作 API Mongoose。有一些資料模型
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. 并且回應資料必須包括User資料以及image url與User. 我試過這個來獲取評論資料
const comments = await Comment.find({post: req.params.postId}).populate("user")
它回傳Comment了User資料,但不包括Image. 我如何執行該查詢?
uj5u.com熱心網友回復:
試試這個(使用帶有物件配置的 pupulate 方法):
const comments = await Comment.find({post: req.params.postId}).populate({
path: 'user',
populate: {
path: 'profilePicture'
}
})
例如,您還可以在此處選擇每個架構的特定欄位。
請讓我知道這對你有沒有用。
參考
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/366988.html
