mongodb 我想把数量和价格相乘

fnvucqvd  于 2023-01-20  发布在  Go
关注(0)|答案(1)|浏览(161)
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(文档));^
服务器错误:汇总期间PlanExecutor错误::原因:无法解析$convert中的数字"",没有onError值:空字符串

ua4mk5z4

ua4mk5z41#

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

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

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

相关问题