Issue with Mongoose: Create operations are not functioning properly right after performing Delete operations

I need to refresh my collection by deleting all existing documents and then repopulating them with new data from an API call. But when I try running the delete operations first, no new documents are created.

Below is a simplified version of my controller function:

let { data } = req.body
try {
    let result = await Record.deleteMany({});
} catch (err) {
    res.status(400).json('Failed to clear database');
}
for (let i in data) {
    await Record.create(data[i]);
}
return res.status(200).json('Successfully Updated Collection')

How can I fix this issue? I just want to remove all existing documents in the collection and then immediately add the new ones.

Answer №1

When working with an array of objects, you can use for of loop to iterate through the data and create new records like so:

let { data } = req.body
for (let newRecord of data) {
    await Record.create(newRecord);
}

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

Every time I check Req.body, it always comes back empty, even after I've already entered information in my form

I am facing an issue with my form where I am trying to input a comment for my shoe and then send it to my node.js server through a POST request. However, the req.body.comment is consistently returning an empty string even when the form is filled out. In m ...

VUE JS - My methods are triggering without any explicit invocation from my side

I've encountered a frustrating problem with Vue JS >.<. My methods are being triggered unexpectedly. I have a button that is supposed to execute a specific method, but this method gets executed along with other methods, causing annoyance... Her ...

Bringing in a legacy ES5 module for integration within a ReactJS component

Attempting to incorporate an ES5 module into a new ReactJS application has been quite the challenge. I'm struggling with understanding the correct way to import the module so that the main function within it can be accessed and executed. Currently, m ...

What is the best way to customize the link style for individual data links within a Highcharts network graph?

I am currently working on creating a Network Graph that visualizes relationships between devices and individuals in an Internet of Things environment. The data for the graph is extracted from a database, including information about the sender and receiver ...

Update the message displayed in the user interface after the view has been fully rendered in an Express application, following the execution of asynchronous

I have created a simple express app that reads files from a directory, renames them, zips the files asynchronously, and then renders another view. The file reading and renaming are done synchronously, while the zipping part is handled asynchronously. My cu ...

In my Vue watch method, I have two parameters specified, and one of them remains constant without any changes

Currently, I am attempting to access a method within my watch function with two parameters. Here is the code snippet for the method: onBoolianChange(value, willChange) { willChange = (value === false) ? true : false; }, watch: { "e ...

AngularJS deferred rendering (not deferred loading views)

Imagine having over 3000 items to display within a fixed-height div using an ng-repeat and setting overflow: auto. This would result in only a portion of the items being visible with the rest accessible via scrollbar. It's anticipated that simply run ...

Using JavaScript, redirect to a specified URL once a valid password has been entered on an HTML form

Need help with JavaScript for password validation and URL redirection. I'm new to JS and used some resources like Password correct? then redirect & Adding an onclick function to go to url in javascript?. Here's my current code: ...

Facing issues connecting to my MongoDB database as I keep encountering the error message "Server Selection Timed Out After 3000ms" on MongoDB Compass

I am encountering an error on my terminal that says: { message: 'connect ECONNREFUSED 127.0.0.1:27017', name: 'MongooseServerSelectionError', reason: TopologyDescription { type: 'Single', setName: null, maxS ...

The display of website content across various screens

I'm relatively new to creating websites using scripts, CSS, etc. But I feel like I'm getting the hang of it pretty well... Now I've reached a point where I want my site to look good on different screen resolutions. Currently, I have somethin ...

The Bootstrap carousel controls now add the carousel ID to the address bar instead of just moving to the next slide

I can't figure out why my carousel isn't working. The id of the carousel is showing up in the webpage's address, which usually happens when the 'bootstrap.js' file is missing, but I have included it. Can anyone help me troubleshoo ...

Serving images using ExpressJS static middleware

I have browsed through multiple discussions on this topic, but none of them seem to address my specific issue. My problem involves trying to serve images statically from NodeJS using ExpressJS. I've been able to successfully serve a CSS file using th ...

Generating a list of objects from an array of strings

I am currently facing an issue in my code and I could use some help with it. Below are the details: I have a array of string values containing MAC addresses and constant min & max values. My goal is to map over these MAC values and create an array of obje ...

"Trying to refresh your chart.js chart with updated data?”

Greetings! I have implemented a chart using chart.js and here is the corresponding code: let myChart = document.getElementById('myChart').getContext('2d'); let newChart = new Chart(myChart, { type: 'line', data: { labels: ...

Tips for adding animation to a React state value change triggered by an input

In my React application, I have a form with multiple fields that each contain a text input and a range input. Currently, both inputs share the same state value and onChange function to keep them synchronized. However, I would like to add an animation effe ...

Guide on transferring Javascript array to PHP script via AJAX?

I need to send a JavaScript array to a PHP file using an AJAX call. Here is the JavaScript array I am working with: var myArray = new Array("Saab","Volvo","BMW"); This JavaScript code will pass the array to the PHP file through an AJAX request and displ ...

Encountered difficulty retrieving properties from the req.query object within expressjs

My setup includes a router configuration like this: router.get('/top-5-cheap', aliasTopTours, getAllTours); I've also implemented some middlewares: Middleware aliasTopTours: In this middleware, I am setting certain properties on the reque ...

Developing a vanilla JavaScript web component with distinct HTML and JavaScript files

As I delve into creating vanilla JS web-components, I am exploring methods to keep the template HTML separate from the JS file, ideally in a distinct HTML file. I have examined various implementations of native JS web-component setups found notably here, ...

What is the best way to transmit extra data when tunneling a TLS connection?

I have developed a basic HTTP proxy that utilizes the HTTP CONNECT method for HTTP tunneling. const http = require('http'); const https = require('https'); const pem = require('pem'); const net = require('net'); con ...

mongoose: uniqueness constraint not being enforced

I am currently seeking information on how to ensure uniqueness for a field that is not an index. I have come across a similar question here, but the solution of using dropDups: true has been deemed outdated. What is the proper method for enforcing unique ...