简体   繁体   English

mongoDB 聚合 $lookup 在 Node.js 中无法正常工作

[英]mongoDB aggregate $lookup not working properly in Node.js

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.它要么什么都不显示,要么显示每个产品的所有 4 个名称。

code in helper.js file: helper.js 文件中的代码:

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在上面的代码CART_COLLECTION & PRODUCT_COLLECTION是来自 MongoDB 数据库的 2 个集合

code from user.js file user.js 文件中的代码

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):来自 cart.hbs 文件的代码(用于显示购物车页面):

            <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:当我尝试将foreignField:'objectId(_id)'更改为foreignField:'_id'时,我没有显示任何对象:

[
  {
    _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.我想要数组中只有一个[Object]的输出,以便购物车项目正确显示。

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.试了很多次都没有效果,求朋友们给个解决办法。

Your $lookup stage should be:您的$lookup阶段应该是:

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

Sample Mongo Playground示例 Mongo Playground

The reason why you get the product with more than 1 item as:您获得超过 1 件product的原因如下:

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

From localFieldlocalField

If an input document does not contain the localField, the $lookup treats the field as having a value of null for matching purposes.如果输入文档不包含 localField,则 $lookup 将该字段视为具有 null 值以进行匹配。

and foreignFieldforeignField

If a document in the from collection does not contain the foreignField, the $lookup treats the value as null for matching purposes.如果 from 集合中的文档不包含 foreignField,则 $lookup 将该值视为 null 以进行匹配。

Both localField and foreignField will be null , thus the matching condition will be true and match all the documents. localFieldforeignField都将为null ,因此匹配条件为true并匹配所有文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM