Home > database >  My findIndex is not working as should using Node.js and mongo DB as database
My findIndex is not working as should using Node.js and mongo DB as database

Time:10-22

Ihave some issues trying to find a index of an expecific product in a mongo database.

const cart = await this.model.findOne({ user: { $eq: user } });
      
 if (cart) {
        const itemFound = cart.products.findIndex(
          (item) => item._id === new ObjectId(obj._id)
        );

I'm sending the id from the frontend as a string and I transform it with the new ObjectId, the issue is it gives me -1, when I console log the item._id and new ObjectId(obj._id). Are the same but I dont know why it gives me -1.

this is the whole fuction I want to do:


async editCart(obj, user) {
   
    try {
      const cart = await this.model.findOne({ user: { $eq: user } });
      
      if (cart) {
        const itemFound = cart.products.findIndex(
          (item) => item._id === new ObjectId(obj._id)
        );
        if (itemFound !== -1) {
          let product = cart.products[itemFound];
          product.count  = obj.count;
          const saved = await cart.save();
          return saved;
        } else {
          cart.products.push(obj);
          const saved = await cart.save();
          return saved;
        }
      } else {
        const newCart = new this.model({
          products: obj,
          user: user,
        });
        const saved = await newCart.save();
        return saved;
      }
    } catch (error) {
      logger.error(`Error to edit cart ${error}`);
      throw new Error(error);
    }
  }

If you find another way to do it I will be really greatfull

CodePudding user response:

You can use .toString() when you want to compare to ObjectId values:

const itemFound = cart.products.findIndex(
  (item) => item._id.toString() === obj._id.toString()
);
  • Related