餐廳是一個集合,具有如下物件:
{
_id: new ObjectId("61723c7378b6d3a5a02d908e"),
name: 'The Blue Hotel',
location: 'Noon city, New York',
phoneNumber: '122-536-7890',
website: 'http://www.bluehotel.com',
priceRange: '$$$',
cuisines: [ 'Mexican', 'Italian' ],
overallRating: 0,
serviceOptions: { dineIn: true, takeOut: true, delivery: true },
reviews: [
{
_id: new ObjectId("61736a0f65b9931b9e428789"),
title: 'asd',
reviewer: 'khoh',
rating: 3,
dateOfReview: '5/12/2002',
review: 'hey'
},
_id: new ObjectId("61736a0f65b9931b9e428790"),
title: 'dom',
reviewer: 'firuu',
rating: 4,
dateOfReview: '25/1/2002',
review: ' bruh'
}
]
}
我正在使用以下代碼根據提供的評論 ID 查找此物件
async get(reviewId) {
const restaurantsCollection = await restaurants();
reviewId = ObjectId(reviewId)
const r = await restaurantsCollection.findOne({reviews: {$elemMatch: {_id: reviewId}}})
return r
這將回傳餐廳集合中的整個物件,如果我只想顯示其 ID 在 get(reviewID) 中提供的評論,我該怎么辦
輸出:
{
_id: new ObjectId("61736a0f65b9931b9e428790"),
title: 'dom',
reviewer: 'firuu',
rating: 4,
dateOfReview: '25/1/2002',
review: ' bruh'
}
uj5u.com熱心網友回復:
使用投影,指定要回傳的欄位
以下僅回傳在 get(reviewID) 中提供 id 的評論
async get(reviewId) {
const restaurantsCollection = await restaurants();
reviewId = ObjectId(reviewId)
const r = await restaurantsCollection.findOne(
{ reviews: { $elemMatch: { _id: reviewId } } },
{ "reviews.$": 1 }
)
return r
}
在這里測驗
您也可以使用 find 而不是 FineOne
uj5u.com熱心網友回復:
詢問
- 更換
ObjectId("61736a0f65b9931b9e428789")用reviewId - 這將回傳與
_id陣列中的匹配的評論 - 如果您只想獲得第一個,以防總是最多 1 個,您可以將最后一個專案替換為
{"$project": {"_id": 0, "review": {"$arrayElemAt": ["$reviews", 0]}}}
*不確定這是否是您需要的
測驗代碼在這里
aggregate(
[{"$match": {"reviews._id": ObjectId("61736a0f65b9931b9e428789")}}
{"$set":
{"reviews":
{"$filter":
{"input": "$reviews",
"cond":
{"$eq": ["$$this._id", ObjectId("61736a0f65b9931b9e428789")]}}}}},
{"$project": {"_id": 0, "reviews": 1}}])
uj5u.com熱心網友回復:
這可能不是您問題的正確答案,但您可以嘗試這樣的方法。
const r = await restaurantsCollection.findOne({reviews: {$elemMatch: {_id: reviewId}}})?.reviews.find(review => review._id.equals(reviewId))
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/333826.html
下一篇:如何手動修復npm漏洞?
