【发布时间】:2021-05-23 02:04:17
【问题描述】:
我正在尝试制作一个返回用户是否收藏的函数。
我在 User 模型上使用 MongoDB 聚合,并使用带有管道和 $project 的收藏模型(所有收藏的用户都保存在其中)的lookout
这里是 MongoDB 聚合函数查询
await User.aggregate([
{
$match: {
_id: ObjectId(_id),
},
},
{
$lookup: {
from: 'userportfolios',
localField: '_id',
foreignField: 'user',
as: 'user_portfolios',
},
},
{
$lookup: {
from: 'favourites',
pipeline: [
{
$match: {
user: ObjectId(data.user._id),
favourites: {
$elemMatch: {
$eq: ObjectId(_id),
},
},
},
},
{
$project: {
_id: 0,
is_favourite: {
$cond: [
{ $ifNull: ['$is_favourite', false] },
{ $literal: true },
{ $literal: false },
],
},
},
},
],
as: 'is_favourite',
},
},
]);
我得到了这个结果
[
{
"_id": "602b5078e8eb5339e0134351",
"is_active": true,
"is_admin": false,
"is_block": false,
"user_type": "company",
"firstName": "Sagar",
"lastName": "Davara",
"mobileNumber": "*******",
"email": "s*********@gmail.com",
"password": "b7370338e54b1cb051be0dd54eba2f7f",
"verificationCode": "210768",
"createdAt": "2021-02-16T04:56:24.091Z",
"updatedAt": "2021-02-16T04:56:24.091Z",
"user_portfolios": [],
"is_favourite": [
{
"is_favourite": false
}
]
}
]
但我想获得 is_favourite: true 而不是对象数组
我需要 mongodb 的这个输出
[
{
"_id": "602b5078e8eb5339e0134351",
"is_active": true,
"is_admin": false,
"is_block": false,
"user_type": "company",
"firstName": "Sagar",
"lastName": "Davara",
"mobileNumber": "6353764283",
"email": "sagardspeed3@gmail.com",
"password": "b7370338e54b1cb051be0dd54eba2f7f",
"verificationCode": "210768",
"createdAt": "2021-02-16T04:56:24.091Z",
"updatedAt": "2021-02-16T04:56:24.091Z",
"user_portfolios": [],
"is_favourite": false
}
]
【问题讨论】: