Mastering the art of inserting or updating data in a database using ExpressJS

I am trying to update the database value if it does not exist, and insert data if it does. I have attempted a method but unfortunately, it was not successful. Can anyone help me figure out how to achieve this efficiently?

fetchRecordFromFile.forEach(el => {
    if(getDataFromDB.indexOf(el.city) > -1)
        {
            Post.create(el ,function(err,data_news){
                if(err){
                    console.log(err)
                }
                else{
                    console.log("Inserted which are not before into database")
                }
            })
        }
});

Answer №1

Adding data to a database is an operation that occurs asynchronously. Therefore, when performing these operations in a loop, it's important to use for-in loops.

To improve the function, consider implementing the following changes:

async function insertRecords() {
  for (const record of fetchRecordFromFile) {
    const cityRecord = await Post.find({city: record.city});
    if (!cityRecord[0]) {
      try {
        const dbRecord = await Post.create(record);
        console.log("Data inserted into the database successfully");
      } catch (error) {
        console.log(error);
      }
    } else {
      console.log('Record already exists');
      // Add update logic here
      // For example:
      // const recordUpdate = await Post.update(cityRecord[0].id, record);
    }
  }
}

Answer №2

It's always advisable to avoid performing a database query within a loop. Instead, consider using insertMany when you need to add multiple items and then analyze the result.nModified or any related field to verify how many documents were successfully inserted.

If your goal is to update existing data or introduce new data with the help of $set or $unset operator, opt for UpdateMany.

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

Modify property page configurations in Visual Studio C 2010 Express

A while ago, I made some adjustments to the Property Pages and Configuration Properties, such as the output directory and code generation settings. Now I want to revert back to the default settings. Despite trying to reset all environment settings using th ...

Guide to building a simple AngularJS webpage to fetch and display RESTful JSON data

I am in the process of developing a simple webpage that displays data retrieved from http://rest-service.guides.spring.io/greeting. The JSON output looks like this: {"id":2273,"content":"Hello, World!"} This is the HTML code I am using: <body ng-app ...

How can we structure relational data in JSON that cannot be easily categorized together?

Hey there, I'm new around here so please bear with me if this question seems basic. Could you point me in the right direction for resources? Consider this sentence: "This approach combines the best of both worlds." Now let's say I want to hi ...

JQuery GET brings back unnecessary HTML content

Currently utilizing a PHP cart class and implementing some jQuery to dynamically update a div when users add products. The issue I'm encountering is that upon adding a product, the list of products on the HTML page gets duplicated (see screenshot) ev ...

Transforming the AggregationOutput into a JsonObject

I wrote a program that runs MongoDB queries using the JAVA driver. The results are stored in AggregationOutput, which I now need to convert into JsonObject and pass it to another function. Here is my code snippet: public class JavaAggregation { public ...

Unable to receive URL parameters using JavaScript on a mobile device

I have been developing a program that displays all users' buttons on a screen, except for the current user's buttons. I came across this code snippet to extract URL parameters: function getParameterByName(name, url) { if (!url) url = window.lo ...

Access an HTML element and using JavaScript to make changes to it

As a new web developer, I am eager to create a grid of file upload zones on my site. I have decided to use DropZone.js for this project. I have customized DropZone and added multiple drop zones in the HTML. The grid layout consists of four rows with four ...

Managing multiple sets of radio buttons using the useState hook

Within my renderUpgrades-function, I handle the options of an item by including them in radio-button-groups. Each item has multiple options and each option has its own radio-button-group. Typically, a radio-button-group can be managed using useState, wit ...

React and Express working together, encountering a 404 error at the endpoint

Encountering a 404 error on the client side. Seeking help to troubleshoot the issue. Came across a solution suggesting to delete node_modules and package-lock, run npm i, but unfortunately, it did not work for me. Server: index.js const express = require( ...

Transforming CSV CSS values with jQuery's CSS method: Step-by-step guide

My goal is to stack multiple background images within a single div container while ensuring their position is relative to the screen height. The problem I'm encountering is my inability to modify CSS values separated by commas. Here is my logical appr ...

Searching with multiple parameters in MongoDB

In my database schema, I have defined various fields such as creatorId, roommatePreference, roomInfo, location, pricing, availability, amneties, rules, photos, description, and status. Each field serves a specific purpose in listing a room for rent. The c ...

Store the JSON reply as a fixed variable

Recently, I have been delving into ReactJS and I've encountered a challenge of saving a JSON array as a 'const'. I have attempted the following approach: fetch(url) .then(response => response.json()) .then(json => { this.setSt ...

Tips for Determining the Lifecycle of a REST API Response

I am in the process of developing REST APIs using NodeJS and the Express framework. The User API is one of them. However, I am uncertain about how to properly handle responses for each scenario within the API. The sequence of sending response HTTP status c ...

Tips for Making Your Popup Window Stand Out

Looking to design a unique pop-up window featuring three tree-style radio buttons and a single submit button. Upon selecting one of the radio buttons, the chosen value should be recorded in the parent window. ...

Having trouble retrieving properties from a JavaScript JSON object?

I am currently working with a JSON object that contains properties for MAKEs, MODELs, YEARs, STATEs, PLATEs, and COLORs. There are 4 instances of each property within the object: Object {MAKE1="xxx ", MODEL1='xxx', YEAR1='xxx', STATE1= ...

What is the process for submitting a form in Laravel 5 with ajax?

Struggling with understanding how to create an ajax post in Laravel. I would like to display errors using jQuery after validation, but I'm unsure about accessing the object sent to my controller and what needs to be 'returned' in the control ...

Leveraging Server Response Codes Across Different Domains Using JavaScript

Before anything else, I must acknowledge the cross-domain issues that may arise with JavaScript. The fact that I am seeing both 404 and 200 response codes in my console has made me reconsider this possibility. The scenario... I am currently developing a w ...

Retrieving the input[text] value in TypeScript before trimming any special characters

One of the tasks I am working on involves a form where users can input text that may contain special characters such as \n, \t, and so on. My objective is to replace these special characters and then update the value of the input field accordingl ...

Zooming in with Three.js OrthographicCamera by focusing on the cursor位置

In my Three.js project, I am using an OrthographicCamera and OrthographicTrackBallControls for zooming and panning. I am attempting to implement a functionality to zoom to the cursor position, but so far, I have been unsuccessful. To start, here is how I a ...

Is there a way to redirect links within an iframe when a user decides to open them in a new tab?

I am currently developing a web application that allows users to access multiple services, such as Spark and others. When a user selects a service, like Spark for example, the app will open a new tab displaying my page (service.html) with user information ...