【问题标题】:how to display cart items in cart pages with node js如何使用节点 js 在购物车页面中显示购物车项目
【发布时间】:2021-02-24 02:48:11
【问题描述】:

这是我使用的代码

getCartProducts:(userId)=>{
    return new Promise(async(resolve,reject)=>{
      let cartItems = await db.get().collection(collection.CART_COLLECTION).aggregate([
        {
          $match:{user:objectId(userId)}
        },
        {
          $lookup:{
            from:collection.PRODUCT_COLLECTION,
            let:{prodList:'$products'},
            pipeline:[
              {
                $match:{
                  $expr:{
                    $in:['$_id',"$$prodList"]
                  },
                },
              },
            ],
            as:'cartItems'
          }
        }
      ]).toArray()
      
      resolve(cartItems)
    })
  }

路由器代码:-

router.get('/cart',varifiedLogin,async(req,res)=>{
  
  let products = await userHelpers.getCartProducts(req.session.user._id)
  console.log(products);
  
  res.render('user/cart')
})

我得到的输出:-

[
  {
    _id: 5fac03eed5f7b103a8906c03,
    user: 5fa8f0dbd417a11f6db37544,
    products: [
      5fac03eed5f7b103a8906c02,
      5fac06f454045e0403e470e0,
      5fac268d2071f006ff398666
    ],
    cartItems: []
  }
]

这是预期的输出。我应该在 cartItems 中获取对象。 _id 是产品编号 具有用户 ID 的用户字段 我添加到购物车的产品有 3 件商品。 在购物车项目中,我需要将产品作为数组获取。

[
  {
    _id: 5fac03eed5f7b103a8906c03,
    user: 5fa8f0dbd417a11f6db37544,
    products: [
      5fac03eed5f7b103a8906c02,
      5fac06f454045e0403e470e0,
      5fac268d2071f006ff398666
    ],
    cartItems: [[Object],[Object]]
  }
]

【问题讨论】:

    标签: node.js mongodb express mongodb-query node-modules


    【解决方案1】:

    $in 中使用第二个参数的数组。 $in 正好有 2 个参数。

    像这样-

    $in: ['$_id', ["$$prodList"]]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-30
      • 1970-01-01
      • 2013-09-11
      • 2019-09-18
      相关资源
      最近更新 更多