我使用聚合從 Mongodb 中的 Posts 集合中獲取結果,我嘗試使用 $lookup 來獲取對用戶集合的資料參考,但結果不是我所期望的
這是我的帖子模型架構:
const Posts = new mongoose.Schema({
postTitle: {
type: String,
required: [true, "Post title must be not empty!"],
trim: true,
maxlength: [150, "Post title can not be more than 150 characters!"]
},
postContent: {
type: String,
required: [true, "Post content must be not empty!"],
trim: true,
maxlength: [50000, "Post content can not be more than 50,000 characters!"]
},
postAuthor: {
type: Schema.Types.ObjectId,
required: true,
ref: 'users'
}
}, {
timestamps: { createdAt: true, updatedAt: true },
versionKey: false
})
export const PostModel = mongoose.model('posts', Posts);
這是我在宣告的聚合中的代碼:
const doc = await PostCollection.aggregate([
{
"$lookup": {
"from": "users",
"localField": "users._id",
"foreignField": "postAuthor",
"as": "postAuthor"
}
},
{
"$project": {
"_id": 0,
"id": "$_id",
"title": "$postTitle",
"content": "$postContent",
"user": "$postAuthor"
}
}
])
console.log(doc)
執行后我得到了結果:
[
{
id: "616e9df6039f4b9f66ce07e0",
title: "title book 1",
content: "content book 1",
user: [
{
_id: "616e9e27cf2f12ba06dd92c9", // author of book 1
name: "John"
},
{
_id: "616e9e3354973970851d1591",
name: "Robinson"
}
]
},
{
id: "616e9e16e2db14f41b82fd8f",
title: "title book 2",
content: "content book 2",
user: [
{
_id: "616e9e27cf2f12ba06dd92c9",
name: "John"
},
{
_id: "616e9e3354973970851d1591", // author of book 2
name: "Robinson"
}
]
}
]
我只想得到這樣的結果:
[
{
id: "616e9df6039f4b9f66ce07e0",
title: "my title book 1",
content: "my content book 1",
user: [
{
_id: "616e9e27cf2f12ba06dd92c9", // author of book 1
name: "John"
}
]
},
{
id: "616e9e16e2db14f41b82fd8f",
title: "my title book 2",
content: "my content book 2",
user: [
{
_id: "616e9e3354973970851d1591", // author of book 2
name: "Robinson"
}
]
}
]
以及在 Posts Collection 中插入的示例資料:
| _ID | 帖子標題 | 帖子內容 | 郵遞員 |
|---|---|---|---|
| 616e9df6039f4b9f66ce07e0 | 書名1 | 我的內容書 1 | 616e9e27cf2f12ba06dd92c9 |
| 616e9e16e2db14f41b82fd8f | 書名2 | 我的內容書 2 | 616e9e3354973970851d1591 |
uj5u.com熱心網友回復:
根據檔案https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/,試試這個
const doc = await PostCollection.aggregate([
{
"$lookup": {
"from": "users",
"localField": "postAuthor",
"foreignField": "_id",
"as": "postAuthor"
}
},
{
"$project": {
"_id": 0,
"id": "$_id",
"title": "$postTitle",
"content": "$postContent",
"user": "$postAuthor"
}
}
])
console.log(doc)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/324661.html
