下面是我的代碼,用于顯示作為餐廳集合物件一部分的評論陣列資料:
async get(reviewId) {
const restaurantsCollection = await restaurants();
reviewId = ObjectId(reviewId)
const r = await restaurantsCollection.findOne(
{ reviews: { $elemMatch: { _id : reviewId } } },
{"projection" : { "reviews.$": true }}
)
return r
}
我的物件看起來像:
{
_id: '6176e58679a981181d94dfaf',
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": "6174cfb953edbe9dc5054f99", // restaurant Id
"reviews": [
{
"_id": "6176df77d4639898b0c155f0", // review Id
"title": "This place was great!",
"reviewer": "scaredycat",
"rating": 5,
"dateOfReview": "10/13/2021",
"review": "This place was great! the staff is top notch and the food was delicious! They really know how to treat their customers"
}
]
}
我想要的輸出:
{
"_id": "6176df77d4639898b0c155f0",
"title": "This place was great!",
"reviewer": "scaredycat",
"rating": 5,
"dateOfReview": "10/13/2021",
"review": "This place was great! the staff is top notch and the food was delicious! They really know how to treat their customers"
}
如何在不獲取餐廳 ID 或整個物件的情況下僅將輸出作為評論?
uj5u.com熱心網友回復:
所以查詢運算子,find并findOne不允許“高級”的資料重組。
所以你有兩個選擇:
更常見的方法是在代碼中執行此操作,通常人們要么使用某種東西mongoose post trigger要么使用某種“共享”函式來處理所有這些轉換,這就是避免代碼重復的方法。
使用聚合框架,如下所示:
const r = await restaurantsCollection.aggregate([
{
$match: { reviews: { $elemMatch: { _id : reviewId } } },
},
{
$replaceRoot: {
newRoot: {
$arrayElemAt: [
{
$filter: {
input: "$reviews",
as: "review",
cond: {$eq: ["$$review._id", reviewId]}
}
},
0
]
}
}
}
])
return r[0]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/336667.html
上一篇:洗掉元素后如何回傳陣列?
下一篇:如何在我的演員串列中分隔陣列項?
