我怎么能得到只有数组元素作为输出,而不是整个对象在MongoDB?



下面是我显示评论数组数据的代码,它是餐厅集合对象的一部分:

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或整个对象的情况下将输出仅作为评论?

所以查询操作符,findfindOne不允许"高级"重构数据。

所以你有两个选择:

  1. 更常见的方法是在代码中完成,通常人们要么使用一些mongoose post触发器,要么使用某种"shared"函数处理所有这些转换,这是避免代码重复的方法。

  2. 使用聚合框架,像这样:

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]

最新更新