我正在尝试修改.find()中单个字段的结果以删除不必要的数据。
字段likedBy
(数组)在不包含userId时应返回一个空数组。但是,当likedBy
确实包含userId时,它应该返回仅包含该userId而不是所有userId的数组。
const response = await MyObject.find().lean({
"likedBy": {
"$elemMatch": {
"$eq": body.userId
}
},
});
userId ='id-1'时的当前响应:
{
"_id": "some id",
"...rest of the fields"
"likedBy": [
"id-1",
"id-2",
"id-3",
]
},
我想要什么:
{
"_id": "some id",
"...rest of the fields"
"likedBy": [
"id-1",
]
},
答案 0 :(得分:0)
您可以定义aggregate
管道,并使用$filter
仅返回匹配的数组元素:
YourModel.aggregate([
{
$match: {
"likedBy": body.userId
}
},
{
$project: {
likedBy: {
$filter: {
input: "$likedBy",
as: "likedBy",
cond: {
$eq: [
"$$likedBy",
body.userId
]
}
}
},
otherField: 1
}
}
])
这是mongoplayground上的一个例子。