here are my Schemas :
const property = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
reviews: [{ type: mongoose.Schema.Types.ObjectId, ref: "Review" }],
});
const review = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
text: { type: String, default: null },
author: { type: mongoose.Schema.Types.ObjectId, ref: "Author" },
});
const author = mongoose.Schema({
_id: {type: mongoose.Schema.Types.ObjectId, default: new mongoose.Types.ObjectId()},
name: { type: String, default: "" },
});
Each Property has a review and each Review has an Author,
Here my code its working I have a nested $lookup for reviews and author but the Author is return as Array I want it as object :
Property.aggregate([
{
$match: {
_id: new mongoose.Types.ObjectId(propertyId),
},
},
{
$lookup: {
from: "reviews",
let: {
reviews: "$reviews",
},
pipeline: [
{
$match: {
$expr: {
$and: [{ $in: ["$_id", "$$reviews"] }],
},
},
},
{
$lookup: {
from: "authors",
let: {
author: "$author",
},
pipeline: [
{
$match: {
$expr: {
$and: [{ $eq: ["$_id", "$$author"] }],
},
},
},
{ $unwind: "$author" },
],
as: "author",
},
},
],
as: "reviews",
},
},
]).exec();
Here is what I got as result :
{
_id : 1,
reviews: [{
_id: 1,
text: 'nice view',
author: [{
id: 1,
name: 'Victor'
}]
}]
}
you can see that the Author is return as Array I want it as object :