0

I've been trying to figure out how to push new product to existing cart which I have in my database.

updateOne is searching for a a cart with claimed userId and then ties to insert new product into products array.

Is this how $addToSet is supposed to be used ? Any hints and suggestions to steer me into right direction are much appreciated!

Also I have tried other methods like insert, insertOne, updates and to be honest I am not quite sure which one to use in this situation.

EDIT: Previous message 'Cart already exists' was just my console.log, so the problem is that nothing happens at all, not in mongo or in express, no error messages, I will look at 'possible duplicate' suggestion soon.

Mongoose cart collection :

{
    "products": [{
        "_id": {
            "$oid": "5f948e5bd8615318f662d315"
        },
        "title": "BAND",
        "price": 16,
        "amount": 25
    }],
    "totalPrice": 416,
    "userId": {
        "$oid": "5f940f8876ad3e073a2e1e8b"
    },
    "__v": 0
}

Cart Schema :

const mongoose = require('mongoose');

const cartSchema = new mongoose.Schema(
    {
        userId: {
            type: mongoose.Types.ObjectId,
            ref: "User"
        },
        products: [
            {
                title: String,
                price: Number,
                amount: Number
            }
        ],
        totalPrice: Number
    }
);

const CartModel = mongoose.model('CartModel', cartSchema, "carts");

module.exports = CartModel

Cart :

let cart = null;
const CartModel = require('./cartModel')

module.exports = class Cart {

    static save(product) {

        let cartModel = new CartModel();

        console.log('Product: ' + product)
        if (cart == null) {
            cart = {products: [], totalPrice: 0}
        }

        cartModel.updateOne(
            {
                userId: '5f940f8876ad3e073a2e1e8b'
            },
            {
                $addToSet: {
                    products: [
                        {
                            'title': product.title,
                            'price': product.price,
                            'amount': product.amount
                        }
                    ],
                    totalPrice: product.amount * product.price
                }
            },
            {upsert: true, new: true},
            {multi: true},
            function (err, res) {
                console.log(err, res)
            });
    }

Edit: The solution was in: https://stackoverflow.com/a/46995621/11004824 "The solution is to run functions on a model, not on a instance of it" I had no idea that running on instance of a model doesn't produce good results. My WORKING CODE

let cart = null;
const CartModel = require('./cartModel')

module.exports = class Cart {

    static save(product) {

        console.log('Product: ' + product)
        if (cart == null) {
            cart = {products: [], totalPrice: 0}
        }

        let productObj = {
            'title': product.title,
            'price': product.price,
            'amount': product.amount
        };

        CartModel.update(
            {
                userId: '5f940f8876ad3e073a2e1e8b'
            },
            {
                $push: {
                    products: productObj
                },
                $set: {
                    totalPrice: product.amount * product.price
                }
            },
            {upsert: true, new: true},
            function (error, success) {
                if (error) {
                    console.log(error)
                } else {
                    console.log(success)
                }
            }
        );
    }
2

1 Answer 1

0

$addToSet pushes a value in the array if it's not already present. What you're trying to do is to update the cart using $addToSet. The problem is that you are also trying to update totalPrice using addToSet. Have a look at this Mongo Playground

1
  • Thank you for this valuable information. I've managed to find an answer.
    – Johnn
    Commented Oct 25, 2020 at 8:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.