首页 > 解决方案 > 在nodejs中将数字作为intiger插入mongodb

问题描述

错误

UnhandledPromiseRejectionWarning : MongoError: $multiply only supports numeric types, not string

问题是我已经拿走了购物车中产品的总和。但价格是字符串格式...解析 Int 不起作用有没有办法将数字作为数字插入数据库


添加产品代码

 addProduct: (product, callback) => {
        db.get().collection('product').insertOne(product).then((data) => {
            callback(data.ops[0]._id)
        })

    }

**求和并返回**

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: {
                    item: 1, quantity: 1, product: { $arrayElemAt: ['$product', 0] }
                }
            }
            ,
            {
                $group:{
                    _id:null,
                    total:{$sum:{$multiply:['$quantity','$product.price']}}
                }
            }

        ]).toArray()
        console.log(total[0].total);
        resolve(total)
    })

标签: javascriptnode.jsmongodb

解决方案


推荐阅读