0

I pretty sure this question was asked many items, however I cannot find an answer to my particular problem, which seems very but I just can't seem to get it working. I have a user model with cart schema array embedded in it. I am trying to add an object to an array and if it exists only update quantity and price, if it is doesn't add to an array. what happens with my code is that it adds a new item when array is empty, it updates the item's quantity and price but it doesn't want to add a new item. I read a bit a bout and as far as I understood I cannot use two different db methods in one request. I would appreciate any help on this, this is the first time I am actually using mongooose.

const CartItem = require('../models/cartModel');
const User = require('../models/userModel');

exports.addToCart = (req, res) => {
  const cartItem = new CartItem.model(req.body);
  const user = new User.model();
    User.model
      .findById(req.params.id)
      .exec((err, docs) => {
        if (err) res.sendStatus(404);
        let cart = docs.cart;
        if (cart.length == 0) {
          docs.cart.push(cartItem);
        }
        let cart = docs.cart;
        let isInCart = cart.filter((item) => {
          console.log(item._id, req.body._id);
          if (item._id == req.body._id) {
            item.quantity += req.body.quantity;
            item.price += req.body.price;
            return true;
          }
        });
        if (isInCart) {
          console.log(cart.length)
        } else {
          cart.push(cartItem);
          console.log(false);
        }

        docs.save(function (err, docs) {
          if (err) return (err);
          res.json(docs);
        });
    });
 };

I actually managed to get it working like this

exports.addToCart = (req, res) => {
  const cartItem = new Cart.model(req.body);
  const user = new User.model();
    User.model
      .findById(req.params.id)
      .exec((err, docs) => {
        if (err) res.sendStatus(404);
        let cart = docs.cart;
        let isInCart = cart.some((item) => {
          console.log(item._id, req.body._id);
          if (item._id == req.body._id) {
            item.quantity += req.body.quantity;
            item.price += req.body.price;
            return true;
          }
        });

        if (!isInCart) {
          console.log(cart.length)
          cart.push(cartItem);
        }
        if (cart.length == 0) {
          cart.push(cartItem);
        }

        docs.save(function (err, docs) {
          if (err) return (err);
          res.json(docs);
        });
    });
};

don't know if this is the right way to do it, but I can both add a new product into my array and update values of existing ones

AndrewB
  • 35
  • 2
  • 9
  • Its not possible as you have noticed. You have to do in two queries. Please look at the linked duplicate. – s7vr Mar 03 '18 at 14:24
  • Possible duplicate of [MongoDB: upsert sub-document](https://stackoverflow.com/questions/23470658/mongodb-upsert-sub-document) – s7vr Mar 03 '18 at 14:24
  • I thought that was a problem. However, why it is possible to add a new element when array is empty and then update a value when it is already pushed into array? Aren't these two different methods? – AndrewB Mar 03 '18 at 14:33
  • So the problem is same whether is array is empty or not. You can only run one query which is either update the array or add a element to array at any point. In essence there is no upsert kind functionality for array to take care of this in one update query. – s7vr Mar 03 '18 at 14:56

1 Answers1

-1

Maybe your problem hava a simpler solution: check this page at the mongoose documentation: there is a compatibility issue with some versions of mongoDB and mongoose, maybe you need to edit your model code to look like this:

const mongoose = require("mongoose");

const CartSchema = new mongoose.Schema({
  //your code here
}, { usePushEach: true });

module.exports = mongoose.model("Cart", CartSchema);

You can find more information here: https://github.com/Automattic/mongoose/issues/5924

Hope it helps.

ufollettu
  • 822
  • 3
  • 19
  • 45
  • Thanks, I actually got it working. I edited my post with the code I used, don't if it is the correct way of doing things in mongoose, but hey it works:D – AndrewB Mar 05 '18 at 14:09