首页 > 解决方案 > Can not convert a string to number, (price of a product) which is taken from mongodb collection by query

问题描述

Hai I am new in nodejs and mongodb.I have to find the total price of a shopping cart.But when multiplying product quantity with price ,the price can not convert to number.when using parseInt result shows Nan. Here is my code:

    getTotalAmount: (userId) => {
return new Promise(async(resolve,reject)=>{

    
    let total = await db.get().collection(collection.CART_COLLECTION).aggregate([
        {
            $match: { user: objectId(userId) }
        },
        {
            $unwind: '$products'
        },
        {
            $project: {
                item: '$products.item',
                quantity: '$products.quantity'
            }
        },
        {
            $lookup: {
                from: collection.PRODUCT_COLLECTION,
                localField: 'item',
                foreignField: '_id',
                as: 'product'

            }
        },
        {
            $project: {
                _id: 1, item: 1, quantity: 1, product: { $arrayElemAt: ['$product', 0] }
            }
        },
        {
            $group:
            {
                _id:null,
                total:{$sum:{$multiply:['$quantity',parseInt('$product.price')]}}
            }
        }
        

    ]).toArray()
  
    console.log(total)
    resolve(total)

    }
)

}

result showing:

[ { _id: null, total: NaN } ]

标签: node.jsmongodb

解决方案


您可以使用 $convert 运算符将字符串转换为数字


推荐阅读