gpt4 book ai didi

node.js - 使用管道中数组中的对象值执行 $lookup

转载 作者:行者123 更新时间:2023-12-04 17:14:35 25 4
gpt4 key购买 nike

所以我有 3 个模型 userpropertytestimonials

客户评价有一个 propertyIdmessageuserId。我已经能够通过管道获得每个属性的所有推荐。

Property.aggregate([
{ $match: { _id: ObjectId(propertyId) } },
{
$lookup: {
from: 'propertytestimonials',
let: { propPropertyId: '$_id' },
pipeline: [
{
$match: {
$expr: {
$and: [{ $eq: ['$propertyId', '$$propPropertyId'] }],
},
},
},
],
as: 'testimonials',
},
},
])

返回的属性如下所示

{
.... other property info,
testimonials: [
{
_id: '6124bbd2f8eacfa2ca662f35',
userId: '6124bbd2f8eacfa2ca662f29',
message: 'Amazing property',
propertyId: '6124bbd2f8eacfa2ca662f2f',
},
{
_id: '6124bbd2f8eacfa2ca662f35',
userId: '6124bbd2f8eacfa2ca662f34',
message: 'Worth the price',
propertyId: '6124bbd2f8eacfa2ca662f2f',
},
]
}

用户模式

firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},

属性模式

name: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
location: {
type: String,
required: true,
},

推荐架构

propertyId: {
type: ObjectId,
required: true,
},
userId: {
type: ObjectId,
required: true,
},
testimonial: {
type: String,
required: true,
},

现在的问题是如何$lookup每个推荐的userId,以便显示用户的信息,而不仅仅是每个推荐中的 id?

我希望我的回复结构如下

{
_id: '6124bbd2f8eacfa2ca662f34',
name: 'Maisonette',
price: 100000,
testimonials: [
{
_id: '6124bbd2f8eacfa2ca662f35',
userId: '6124bbd2f8eacfa2ca662f29',
testimonial: 'Amazing property',
propertyId: '6124bbd2f8eacfa2ca662f34',
user: {
_id: '6124bbd2f8eacfa2ca662f29',
firstName: 'John',
lastName: 'Doe',
email: 'jd@mail.com',
}
},
{
_id: '6124bbd2f8eacfa2ca662f35',
userId: '6124bbd2f8eacfa2ca662f27',
testimonial: 'Worth the price',
propertyId: '6124bbd2f8eacfa2ca662f34',
user: {
_id: '6124bbd2f8eacfa2ca662f27',
firstName: 'Sam',
lastName: 'Ben',
email: 'sb@mail.com',
}
}
]
}

最佳答案

你可以把$lookup阶段放在pipeline里面,

  • $lookup 用户集合
  • $addFields, $arrayElemAt 从上面的用户查找结果中获取第一个元素
Property.aggregate([
{ $match: { _id: ObjectId(propertyId) } },
{
$lookup: {
from: "propertytestimonials",
let: { propPropertyId: "$_id" },
pipeline: [
{
$match: {
$expr: { $eq: ["$propertyId", "$$propPropertyId"] }
}
},
{
$lookup: {
from: "users",
localField: "userId",
foreignField: "_id",
as: "user"
}
},
{
$addFields: {
user: { $arrayElemAt: ["$user", 0] }
}
}
],
as: "testimonials"
}
}
])

Playground

关于node.js - 使用管道中数组中的对象值执行 $lookup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68905603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com