lulu33
lulu33

Reputation: 327

Search an array of objects to match objectId from mongodb

I'm trying to search an array of objects by a key that contains nested object id for populating.

My object


{
  service: 'user',
  isModerator: true,
  isAdmin: true,
  carts: [
    {
      _id: 5e1344dcd4c94a1554ae0191,
      qty: 1,
      product: 5e09e4e0fcda6f268cefef3f,
      user: 5e0dda6d6853702038da60f0,
      expireAt: 2020-01-06T14:31:56.708Z,
      __v: 0
    },
    {
      _id: 5e13455306a54b31fc71b371,
      qty: 1,
      product: 5e09e507fcda6f268cefef40,// object ID
      user: 5e0dda6d6853702038da60f0,
      expireAt: 2020-01-06T14:33:55.573Z,
      __v: 0
    },
  ],

I want to match if carts array, contains cart with a product that user is adding, to not add it the second time but instead increment qty of the existing one.


My code

  const itemId = req.body._id;
  const userId = req.user._id;
  const { qty } = req.body;
  try {
    const producto = await Product.findById(itemId);
    const user = await User.findById(userId).populate({
      path: 'carts',
    });
    const result = user.carts.find((o) => {
      console.log(typeof o.product) // returns object
      console.log(typeof producto._id); // returns object
      return o.product === producto._id
    });
    console.log(result); // returns undefined
    if (result !== undefined) {
      const foundCart = await Cart.findById(result._id);
      foundCart.qty += qty;
      await foundCart.save();
      return res.json({ message: 1 });
    }
    const newCart = new Cart({
      qty,
      product: producto,
      user,
    });
    const cart = await newCart.save();
    user.carts.push(cart);
    await user.save();
    return res.json({ message: 1 });
  } catch (error) {
    return console.log(error);
  }

Upvotes: 1

Views: 77

Answers (1)

SuleymanSah
SuleymanSah

Reputation: 17888

I think the problem is this line

  return o.product === producto._id

Can you change it like this and try?

  return o.product.toString() === producto._id.toString()

Upvotes: 2

Related Questions