The mongoose find query is coming back with an empty array, even though there is data present in the

My goal is to update commodity data in my stockrecord collection by adding the quantity of a commodity if it already exists in the collection.

However, I encountered an issue where the find method returns an empty array even for existing data.

Here is the code snippet:

  commodity.map(async (e) => {
    const data = await new Commodity({
      name: e.commodityName,
      units: e.units,
      quantity: e.quantity,
    });
    data.donator = donator;
    await data.save();
    const stock = await StockRecord.find({
      name: {
        $eq: e.commodityName,
      },
    });
    //console.log(stock);

    if (stock.length === 0) {
      const record = await new StockRecord({
        name: e.commodityName,
        units: e.units,
        quantity: parseFloat(e.quantity),
      });
      await record.save();
      console.log(record);
    } else {
      console.log('may sulud');

      stock[0].quantity += parseFloat(e.quantity);
      await stock[0].save();
    }
  });

To understand more about my stockrecord model, check it out here:

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    
    const stockRecordSchema = new Schema({
      name: {
        type: String,
      },
    
      units: {
        type: String,
        enum: \['kg', 'pcs'\],
      },
      quantity: {
        type: Number,
      },
    });

Answer №1

The Array.map method does not support Promises

Consider using

for (const item of commodity) { //perform async operations here }

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

Switching from the global import module pattern to ES6 modules

In recent years, my approach to JavaScript development has involved using the global import method. Typically, I work with a set of utility functions packaged and passed to a separate site module containing individual functions for each web functionality: ...

The JavaScript code is attempting to execute a PHP script, however, I am struggling to parse the JSON data returned for use in the

As a novice, I am in the process of creating a JavaScript function that calls a PHP script every second. The PHP script retrieves values from MySQL DB, encodes them into JSON, which is then decoded by JS to display them on an HTML page. I have two queries ...

Executing a JS function within a table cell

I've been attempting to invoke a function within a table cell to dynamically create some data, but I keep encountering this error below. I'm uncertain whether I'm correctly calling defined functions and JavaScript functions inside the table ...

Challenges with Material UI and Styled Components Overriding

When utilizing Material UI's Typography, everything was functioning perfectly: <Typography component="h1" variant="h5"> Sign in </Typography> However, I decided to transition to styled-components and attempted the foll ...

Using HTML and Javascript files with AJAX can sometimes be problematic due to compatibility issues

Throughout the past seven years, I have dedicated my time to programming small websites for offline and private usage. Each project consists of an html file that links to a css file and a javascript file. The javascript file utilizes AJAX to load content f ...

Ways to stop a ng-click event on a child div controller from activating an ng-click in the parent controller?

http://plnkr.co/edit/gB7MtVOOHH0FBJYa6P8t?p=preview The example above demonstrates a parent-child controller setup. In the child controller, when a button is clicked, it displays the div showPop and emits an event to the $rootScope. Upon receiving this e ...

Storing and Editing Collection of Elements

My latest project involves creating a basic web scraping tool that gathers information on apartment prices from a specific webpage. Each time the tool runs, it compiles an array of objects with details such as date, time, floor plan name, bed number, floor ...

What is the best way to retrieve the most recent CMS posts information within a Gatsby-constructed project?

I created a static website using Gatsby and everything was working well. However, I encountered an issue when updating the titles and content of posts in Contentful CMS - the changes were not reflected when I refreshed the website. How can I ensure that ...

Updating the progress state of MUI linear determinate diligently

I currently have a modal set up that handles some asynchronous logic for submitting data to a database. The component I am using, called LinearDeterminate, is designed using Material-UI. You can find more information about it here: MUI Progress import { u ...

The values are not being displayed in the local storage checkbox

I attempted to transfer checkbox values to another HTML page using local storage, however they were not appearing on the other page Here is my page1 HTML code snippet: <input class="checkbox" type="checkbox" id="option1" name="car1" value="BMW"> ...

Calculating the size of an array based on its attributes

Hey there, I'm working with an array containing attributes and need to determine its length. In this particular case, the array should have a length of 2 since there are only two "items" present. {"items":[{"value":"2","valor":0,"name":"Limpeza"}, {" ...

Display the <div> element at the current scroll position on the page

Alright, I have a challenging question for you! I don't have the ability to search the internet for this one because I can't quite put it into words. All I have are some images and wild guesses on how it's done. Maybe you'll find it int ...

Interactive website featuring 3DSMax .obj and .max models with advanced AJAX clickable functionalities

I have a 3DSMax model in both .obj and .max file formats. This model includes clickable points that work perfectly within 3DSMax, displaying details when clicked. My goal is to showcase this interactive model on the web with all its clickable features int ...

Node.js is executing the CRON process twice

Within my Node.js application, I have set up a CRON job that runs every day at 10 AM to send push notifications to users. However, I am encountering an issue where two notifications are being sent to the user's device each time the CRON job is trigger ...

Many inhabitants - utilizing mongoosejs

Just a simple question, for example with a double reference in the model. Schema / Model var OrderSchema = new Schema({ user: { type : Schema.Types.ObjectId, ref : 'User', required: true }, meal: { ...

The radio button element could not be located using the attribute "checked="Checked""

While working with Geb, I encountered an issue using the code div.find("input","checked":contains("checked")). This is the snippet of code I attempted to use in order to locate the checked radio button on a webpage. However, I received an error when using ...

Exploring the mocking of document,hidden using Jasmine

Struggling to simulate document.hidden in an angular unit test, but facing issues. Tried the following solutions: spyOn(Document.prototype, <any>'hidden').and.returnValue(true); spyOn(Document, <any>'hidden').and.ret ...

Steps to avoid reinitializing the component upon changing routes in an Angular 9 component

In my component, the width of a chart is stored in a variable (because I can't use style for d3). However, every time the route changes, all variables in this class component become undefined. I have tried using ngIf, services (which also become unde ...

Displaying JavaScript array contents in an HTML page without using the .innerHTML property

As someone new to the world of JavaScript and web development, I find myself faced with a challenge. I want to showcase the contents of two different JavaScript arrays in an HTML format. However, my research has led me to believe that utilizing .innerHTML ...

"Encountering an error: invalid CSRF token in Node.js csurf

I have been utilizing the npm module csurf to generate a token. Initially, I retrieve the token from the server and then utilize it for the /register request. When I replicate these steps in Postman, everything seems to function correctly, but unfortunatel ...