Explore an array of elements to find the correct objectId stored in mongodb

element, I am faced with a challenge of searching through an array of objects to find a key that contains nested object id for populating purposes.

Exploring 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
    },
  ],

The goal here is to determine if the carts array already contains a cart with a specific product that a user is attempting to add, in order to prevent duplication and instead increase the quantity of the existing one.


My Implementation

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

Answer №1

It seems like the issue lies within this particular line:

  return o.product === producto._id

Perhaps you could modify it as follows and give it a shot?

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Changing the 'null' string to null in JavaScript

Within an array of objects, some keys have a value of "null" as a string that I want to convert to null. Here is the code I tried: let obj = [{ "fundcode": "DE", "fundname": "Defens", ...

The concept of embedded schemas in Mongoose

Currently working on an app that tracks workouts, and I'm encountering some issues with Mongoose. I have set up two schemas - one for workouts and one for exercises. The goal is to store new exercises within the corresponding workout entry, but I&apo ...

Node.js: Attempting to arrange ISO dates based on their time span

I am currently working on creating a line chart using the chart.js library. In order to do this, I have an array that contains ISO dates and my goal is to determine which ISO dates belong to the same hour and day. This information will then be used to gene ...

Enhance the styling of elements generated through JavaScript in VueJs with custom CSS

I need help applying CSS to elements that I dynamically created using JavaScript. buttonClicked(event) { console.log(event); let x = event.clientX - event.target.offsetLeft; let y = event.clientY - event.target.offsetTop; let ripples = document.cre ...

Delete a particular table while utilizing $.fn.DataTable.tables()

On a single page, I have several tables that need to be removed when the user decides. My approach was to utilize let table = $.fn.DataTable.tables() table[i-1].destroy(); This code is aimed at obtaining an array of all the tables and subsequently destroy ...

Customized placement of form fields on an HTML grid determined by the user

My goal is to organize input elements on a grid based on user preferences. After researching, I stumbled upon CSS grids, which seem promising. I am considering creating a CSS grid with r rows and c columns, then using JavaScript to assign input elements t ...

Execute various settimeout or display functions on various elements of a webpage

Just a heads up, I'm not really experienced in development. More on the newbie side of things, but eager to learn. I've been looking for an answer to my question, but so far haven't come across anything that fits my specific situation. It m ...

Exploring the process of gathering information using Node.js' http.request

I am currently facing a challenge where I need to call a REST API URL in one method and then use the response from that call to form a subsequent query to another URL, let's say git, to fetch some information. Despite browsing through several examples ...

Ways to incorporate conditional checks prior to running class methods

Seeking input on handling async data retrieval elegantly. When initializing a class with asynchronous data, I have been following this approach: class SomeClass { // Disabling strictPropertyInitialization private someProperty: SomeType public asy ...

After making 5 Ajax get requests, there is no response being received

Currently, I'm facing an issue when trying to retrieve information from the MongoDB server to the frontend using an AJAX GET request. Everything works smoothly until I attempt to call the JavaScript function multiple times. Strangely, if I call the fu ...

Is it possible to trigger the alert message by utilizing this code snippet?

Is it possible to display a message using this function? var start_database = function() { alert('hello'); }; window.setTimeout(start_database, 1000); ...

Merge two arrays based on date and sort them using Angular.js/JavaScript

I am facing a challenge where I have two JSON arrays, each containing a field named date. My goal is to compare the two arrays and merge them into a single array. Check out the code snippet below: var firstArr=[{'name':'Ram','date ...

What is the best way to give a fixed height to Card content in Material UI? Is CSS the way to go?

I've been struggling with a design issue involving Material-UI cards used to display News. The problem arises when the paragraph section of the card occupies multiple lines of text. When it spans two lines, there is a 10px spacing between the paragrap ...

Stop users from refreshing or closing the window while an axios request is being processed

I'm in the process of creating a dynamic Web Application that involves utilizing Axios.get requests. Given that Axios operates asynchronously, my approach includes an async function along with await axios.all: async handleSubmit(){ const ...

Can you please explain the purpose of the mysterious JavaScript function f => f?

Currently, I am utilizing a third-party library that utilizes a function with functions as arguments. During my conditional checks, I determine whether to add a particular function as a parameter or not. However, providing null in these cases results in er ...

Passing "this" to the context provider value in React

While experimenting with the useContext in a class component, I decided to create a basic React (Next.js) application. The app consists of a single button that invokes a function in the context to update the state and trigger a re-render of the home compon ...

Verify the string to see if it contains a Steam game key

I am seeking assistance with a task that involves verifying whether a specific string contains a particular pattern: Below are several strings in an array: [ "please use this key: ')D9ad-98ada-jiada-8a8aa'", "kK8AD-AODK8-ADA7A", "heres a fr ...

Using NodeJs to Render HTML Templates and Implement Logic on the Server Side

Hello, I am currently working on developing a widget module for my Angular 1 based UI project. This widget is meant to display real-time information. My design involves sending an HTML view to the client from the Node server (potentially using Express.js) ...

The best way to retrieve information in Express.js is by accessing it from within the

Can I utilize the URL http://localhost:3000/assets/img/1.jpg?50 in place of http://localhost:3000/assets/img/1.jpg/50 app.get('/assets/img/:file/:percentage', (req, res) =>{ loadImagePercent(req, res, "private/img/"+req.param ...

Can GET or POST variables be transmitted to external JavaScript?

Is it possible to pass a variable to an external JavaScript file? For instance: Suppose I have the following code: <script type="text/javascript" src="gallery.js"></script> I'm curious to know if it's feasible to pass an argument ...