【问题标题】:mongoDB aggregate $lookup not working properly in Node.jsmongoDB 聚合 $lookup 在 Node.js 中无法正常工作
【发布时间】:2022-07-21 20:21:20
【问题描述】:

我正在处理一个购物车项目,并希望显示购物车商品的数量。但它不能正常工作。我想显示购物车中的商品数量及其相应的名称,但是当我尝试这个时,输出什么也没有显示。它要么什么都不显示,要么显示每个产品的所有 4 个名称。

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)
    })

在上面的代码中CART_COLLECTION & PRODUCT_COLLECTION 是来自 MongoDB 数据库的 2 个集合

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});
  })
});

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>

当我将数据打印到控制台时,它会显示:

[
  {
    _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] ]
  }
]

当我尝试将 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: []
  }
]

我想要一个在数组中只有一个 [Object] 的输出,以便购物车项目能够正确显示。

购物车集合中的数据:

 { "_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 } 
] }

产品集合中的数据:

    { "_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" }

试了很多次都没用,请朋友们给个解决办法。

【问题讨论】:

    标签: javascript node.js mongodb express handlebars.js


    【解决方案1】:

    您的$lookup 阶段应该是:

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

    Sample Mongo Playground

    您收到product 的原因超过 1 项为:

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

    来自localField

    如果输入文档不包含 localField,则 $lookup 将该字段视为具有 null 值以进行匹配。

    foreignField

    如果 from 集合中的文档不包含 foreignField,则 $lookup 将该值视为 null 以进行匹配。

    localFieldforeignField 都将是null,因此匹配条件将为true 并匹配所有文档。

    【讨论】:

      猜你喜欢
      • 2019-08-30
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 2021-12-01
      • 2018-12-20
      • 1970-01-01
      • 2021-01-01
      • 1970-01-01
      相关资源
      最近更新 更多