A
A
Alexey Yakovlev2020-12-09 21:26:22
MongoDB
Alexey Yakovlev, 2020-12-09 21:26:22

Doesn't push into the array, what's wrong?

You need to add dimensions to the cart object. I found this method on the Internet, but for some reason it does not work, the basket is not updated.

POST request:

router.post('/add', auth, async(req, res) => {
    try {
        const product = await Product.findById(
            req.body.id, req.body.title, req.body.nowPrice, req.body.mainSize,
            req.body.article, req.body.sex
        );

        product.size = req.body.size;

        mongoose.connection.db.collection('products', (err, docs) => {
            Product.findOne((err, result) => {
                if (err) return console.log(err);

                if (result) {
                    Product.update({
                        '$push': {
                            'cart': {
                                'items': {
                                    '$each': product,
                                    'size': {
                                        '$each': product.size
                                    }
                                }
                            }
                        }
                    })

                    res.redirect('/cart');
                } else {
                    res.status(400).send({ message: 'Произошла ошибка' });
                }
            });
        });
    } catch (e) {
        res.status(400).send({ message: 'Произошла ошибка ' + e.message });
    }
})


User Model:
const user = new Schema({
    firstName: String,
    lastName: String,
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    cart: {
        items: [{
            article: {
                type: String,
                required: true
            },
            title: {
                type: String,
                required: true
            },
            count: {
                type: Number,
                required: true,
                default: 1
            },
            price: {
                type: Number,
                required: true
            },
            mainSize: {
                type: String
            },
            size: [{
                type: String
            }],
            productId: {
                type: Schema.Types.ObjectId,
                ref: 'Product',
                required: true
            }
        }]
    }
})

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question