mongoDB aggregate $lookup not working properly in Node.js

Viewed 38

I am working on a shopping cart project and wanted to show cart items with quantity. But its not working properly. I want to show the quantity of items in cart along withits corresponding name, but when I try this the output shows nothing. Either it shows nothing or it shows all 4 name for each product.

code in helper.js file:

getCartProducts:(userId)=>{
    return new Promise(async(resolve,reject) =>{
        let cartItems=await db.get().collection(collection.CART_COLLECTION).aggregate([
            {
                $match:{user:objectId(userId)}
            },
            {
                $unwind:'$products'
            },
            {
                $project:{
                    items:'$products.item',
                    quantity:'$products.quantity'
                }
            },
            {
                $lookup:{
                    from:collection.PRODUCT_COLLECTION,
                    localField:'item',
                    foreignField:'objectId(_id)',
                    as:'product'
                }
            }
        ]).toArray()
        console.log(cartItems);
        resolve(cartItems)
    })

In the above code CART_COLLECTION & PRODUCT_COLLECTION are 2 collection from MongoDB database

code from user.js file

router.get('/cart',verifyLogin, async(req,res) => {
let products= await userHelpers.getCartProducts(req.session.user._id).then((products)=>{
    console.log("The Products are: "+products);
    res.render('user/cart',{products,user:req.session.user});
  })
});

code from cart.hbs file(for displaying cart page):

            <tbody>
                {{#each products}}
                <tr>
                    {{#each this.product}}
                    <td><img src="/product-images/{{this._id}}.png" style="width:100px; height:100px" alt=""></td>
                    <td>{{this.Name}}</td>
                    {{/each}}
                    <td>
                        <button class="cart-item-count m-3">-</button>{{this.quantity}}<button class="cart-item-count m-3">+</button>
                    </td>
                    <td><a href="#" class="btn btn-danger">Remove</a></td>
                </tr>
                {{/each}}
            </tbody>

When i print the data to console it displays this:

[
  {
    _id: new ObjectId("62d90f2ff3d39ad716146cae"),
    items: new ObjectId("62d6fac11b6108a253a6478c"),
    quantity: 3,
    product: [ [Object], [Object], [Object], [Object] ]
  },
  {
    _id: new ObjectId("62d90f2ff3d39ad716146cae"),
    items: new ObjectId("62d6fae31b6108a253a6478e"),
    quantity: 2,
    product: [ [Object], [Object], [Object], [Object] ]
  },
  {
    _id: new ObjectId("62d90f2ff3d39ad716146cae"),
    items: new ObjectId("62d6fad31b6108a253a6478d"),
    quantity: 1,
    product: [ [Object], [Object], [Object], [Object] ]
  },
  {
    _id: new ObjectId("62d90f2ff3d39ad716146cae"),
    items: new ObjectId("62d7fa7b54f0ecc72d85831c"),
    quantity: 1,
    product: [ [Object], [Object], [Object], [Object] ]
  }
]

when I try changing the foreignField:'objectId(_id)' to foreignField:'_id' ith shows no objects:

[
  {
    _id: new ObjectId("62d90f2ff3d39ad716146cae"),
    items: new ObjectId("62d6fac11b6108a253a6478c"),
    quantity: 3,
    product: []
  },
  {
    _id: new ObjectId("62d90f2ff3d39ad716146cae"),
    items: new ObjectId("62d6fae31b6108a253a6478e"),
    quantity: 2,
    product: []
  },
  {
    _id: new ObjectId("62d90f2ff3d39ad716146cae"),
    items: new ObjectId("62d6fad31b6108a253a6478d"),
    quantity: 1,
    product: []
  },
  {
    _id: new ObjectId("62d90f2ff3d39ad716146cae"),
    items: new ObjectId("62d7fa7b54f0ecc72d85831c"),
    quantity: 1,
    product: []
  }
]

I want an output with only one [Object] in the array so the cart items will display properly.

Data in cart collection:

 { "_id" : ObjectId("62d90f2ff3d39ad716146cae"), "user" : ObjectId("62d7a948d05082b22306ff73"), "products" : 
[ 
{ "item" : ObjectId("62d6fac11b6108a253a6478c"), "quantity" : 3 },
 { "item" : ObjectId("62d6fae31b6108a253a6478e"), "quantity" : 2 },
 { "item" : ObjectId("62d6fad31b6108a253a6478d"), "quantity" : 1 },
 { "item" : ObjectId("62d7fa7b54f0ecc72d85831c"), "quantity" : 1 } 
] }

data in product collection:

    { "_id" : ObjectId("62d6fac11b6108a253a6478c"), "Name" : "code", "Category" : "pic", "Price" : "2000", "Description" : "good one" }
{ "_id" : ObjectId("62d6fad31b6108a253a6478d"), "Name" : "Clickrf", "Category" : "picrdf", "Price" : "20002", "Description" : "good onef" }
{ "_id" : ObjectId("62d6fae31b6108a253a6478e"), "Name" : "Click3", "Category" : "pic3", "Price" : "2000.3", "Description" : "good one3" }
{ "_id" : ObjectId("62d7fa7b54f0ecc72d85831c"), "Name" : "Click", "Category" : "pic5", "Price" : "2000.2", "Description" : "good one5" }

I tried so many times but nothing working, please give me a solution friends.

1 Answers

Your $lookup stage should be:

  {
    $lookup: {
      from: collection.PRODUCT_COLLECTION,
      localField: "items",
      foreignField: "_id",
      as: "product"
    }
  }

Sample Mongo Playground

The reason why you get the product with more than 1 item as:

localField:'item',
foreignField:'objectId(_id)',

From localField

If an input document does not contain the localField, the $lookup treats the field as having a value of null for matching purposes.

and foreignField

If a document in the from collection does not contain the foreignField, the $lookup treats the value as null for matching purposes.

Both localField and foreignField will be null, thus the matching condition will be true and match all the documents.

Related