【问题标题】:I want to multiply the quantity and price我想乘以数量和价格
【发布时间】:2023-01-18 01:09:54
【问题描述】:
getTotalAmount: (userId,products) => {    
    return new Promise(async(res,rej) => {
        let total = await db.get().collection(collections.CART_COLLECTION).aggregate([
            {
                $match:{user: ObjectId(userId)}
            },
            {
                $unwind:'$products'
            },
            {
                $project:{
                    item: '$products.item',
                    quantity: '$products.quantity'
                }
            },
            {
                $lookup:{
                    from: collections.PRODUCT_COLLECTION,
                    localField: 'item',
                    foreignField: '_id',
                    as: 'product'
                }
            },
            {
                $project:{
                    item:1,quantity:1,product:{$arrayElemAt:["$product",0]}
                }
            },
            {
                $group: { 
                    _id: null,
                    total: {
                        $sum: {
                            $cond: {
                                if: {$ifNull: [ "$product.OfferPrice", false ]},
                                then: {$multiply: [{ $toDecimal: '$quantity' }, {$convert: {input: {$ifNull: ["$product.OfferPrice", 0]}, to: "double"}}]},
                                else: {$multiply: [{ $toDecimal: '$quantity' }, {$convert: {input: { $ifNull: ["$product.Price", 0] }, to: "double"}}]}
                            }
                        }
                    }
                }
            }
        ]).toArray()
        // console.log(total)
            res(total[0].total) 
    })

回调(新错误_1.MongoServerError(文档)); ^

MongoServerError: PlanExecutor error during aggregation :: caused by :: Failed to parse number '' in $convert with no onError value: 空字符串

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    您可以使用以下方法解决此问题 -

    {$convert: {input: "$product.Price", onNull: 0, to: "double"}}
    

    或者,您可以通过错误:0也作为安全检查。 参考 - https://www.mongodb.com/docs/manual/reference/operator/aggregation/convert/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-29
      • 1970-01-01
      • 2019-08-24
      • 1970-01-01
      • 2016-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多