不能将字符串转换为数字,(产品的价格),该数字是通过查询从mongodb收集的



我是nodejs和mongodb的新手。我必须找出一辆购物车的总价。但当产品数量与价格相乘时,价格不能转换为数字。当使用parseInt时,结果显示Nan。下面是我的代码:

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

}

结果显示:

[{_id: null, total: NaN}]

可以使用$convert操作符

将字符串转换为数字

最新更新