Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 在mongoose中多次添加同一产品时如何更新购物车_Node.js_Mongodb_Express_Mongoose - Fatal编程技术网

Node.js 在mongoose中多次添加同一产品时如何更新购物车

Node.js 在mongoose中多次添加同一产品时如何更新购物车,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,当产品在购物车中添加多次时,无法更新项目数量。参数为用户id和产品id 当第一个产品添加到购物车中并推送独特的产品时,我正在创建购物车。但是,当第二次添加相同的产品时,我想更新产品质量x2,而不是添加整个记录 这是我的密码: router.get('/add-to-cart/:userID/:id', function (req, res, next) { var productId = req.params.id; var userId = req.params.userID;

当产品在购物车中添加多次时,无法更新项目数量。参数为用户id和产品id 当第一个产品添加到购物车中并推送独特的产品时,我正在创建购物车。但是,当第二次添加相同的产品时,我想更新产品质量x2,而不是添加整个记录

这是我的密码:

router.get('/add-to-cart/:userID/:id', function (req, res, next) {
    var productId = req.params.id;
    var userId = req.params.userID;
    Cart.findOne({ user: userId }, (err, doc) => {
    if (err) res.send(err);
    if (doc == null) 
    { 
        var cart = new Cart;
        Product.findById(productId, (err, product) => {
        if (err) console.error(err);
        let item={
            id:product._id,
            name:product.name,
            price:product.price,
            subtotal:product.price*1,
            qty:1
        }
        cart.items.push(item);
        cart.user = userId; // set cart user
        cart.totalPrice = item.price * item.qty;
        cart.totalQty ++;
        cart.save((err, data) => {
            if (err)  res.send(err);
                    res.json(cart);
            });
        });
    }

    else{
        Product.findById(productId, (err, product) =>{
        let item={
            id: product._id,
            name: product.name,
            price:product.price,
            subtotal:product.price*1,
            qty:1
        }
        doc.items.push(item);
        doc.save(err,data=>{
            res.json(doc);
        })
        doc.totalQty ++;
        doc.totalPrice += item.price*item.qty;


    })
    }
})
});
module.exports=路由器

这是我的购物车模式

const mongoose = require("mongoose");
var schema = mongoose.Schema;
// sample user schema
var CartSchema = new mongoose.Schema({
    product: {type: mongoose.Schema.Types.ObjectId,ref: 'Product'},
    totalQty:{type: Number,default: 0},
    totalPrice: {type: Number,default: 0},
    items : Array,
    user:{type: mongoose.Schema.Types.ObjectId,ref: 'User'}
});
module.exports =  mongoose.model('Cart', CartSchema); 

同时放置您的模式…是更新了模式