Hellow freinds! i have a problem with aggregate in my project.
i have two collection that i want to select them by lookup. the first one is Cart:
const mongoose = require("mongoose")
const Schema = mongoose.Schema
const cartSchema = new Schema({
product_id : {type : mongoose.ObjectId},
user_cookie : {type : String},
user_session : {type : String}
})
module.exports = mongoose.model("Cart", cartSchema, "Cart")
the second one is Product:
const mongoose = require("mongoose")
const Schema = mongoose.Schema
const productSchema = new Schema({
name : {type : String},
canonical : {type : String},
no_index : {type : Boolean},
category : {type : String},
category_url : {type : String},
description : {type : String},
content : {type : String},
image : {type : String},
alt : {type : String},
url : {type : String},
meta_keywords : {type : String}
})
module.exports = mongoose.model("Product", productSchema, "Product")
the Cart.product_id is equal to Product._id. i also have a condition. the Cart.user_cookie should be equal to req.cookies.cookieName.
const results = await Cart.aggregate([
{
$lookup: {
from: "Product",
let: { ids: ["$product_id"] },
pipeline: [
{
$match: {
$expr: {
$in: ["$_id", "$$ids"]
}
}
},
{
$match: {
$expr: {
$eq: ["$user_cookie", req.cookies.cookieName]
}
}
}
],
as: "joinedData",
}
},
{
$unwind: "$joinedData"
}
]);
The output should be something like this:
results[
{
"_id": {
"$oid": "65f484de010a337f71756933"
},
"product_id": {
"$oid": "65f1d6b5a62a676f3a7b84af"
},
"user_cookie": "05230045185837191",
"user_session": "",
"name": "dddd",
"canonical": "",
"no_index": true,
"description": "",
"content": "",
"image": null,
"alt": "",
"url": "",
"meta_keywords": "",
"__v": 0
},
{
"_id": {
"$oid": "65f4901d452327129855281b"
},
"product_id": {
"$oid": "65f1d6b5a62a676f3a7b84af"
},
"user_cookie": "05230033185837191",
"user_session": "",
"name": "dddd",
"canonical": "",
"no_index": true,
"description": "",
"content": "",
"image": null,
"alt": "",
"url": "",
"meta_keywords": "",
"__v": 0
}
]
I would be very grateful if you could solve my problem.