Script to populate database using Mongoose gets stuck

I'm currently dealing with the following script:

const db = require('../db')
const User = require('../models/user')

db.on('error', console.error.bind(console, 'MongoDB connection error:'))

const main = async () => {
    const users = [
        new User({ name: 'Benny', age: 28, status: 'active' }),
        new User({ name: 'Claire', age: 28, status: 'active' })
    ]
    const newUsers = async () => {
        await users.forEach(async user => await user.save())
    }
    await newUsers()
    console.log("Created users!")
}

const run = async () => {
        await main()
        process.exit(0)
}

run()

The issue I'm facing is that process.exit() seems to be running before main() completes its execution, resulting in no users being created.

If I remove process.exit(), the script runs successfully but hangs indefinitely.

So, how can I ensure that my script both executes properly and exits after completion?

Answer №1

Attempting to await users.forEach() is ineffective because the method forEach does not have a return value to wait for. It likely iterates through the entire list and exits immediately, leading to a premature exit from main and triggering process.exit() before the .save() operations are completed.

Instead of waiting on each individual operation, you can utilize Promise.all() to ensure all promises are resolved. This involves mapping each user creation to a Promise, which aligns with how your User.save function already operates. Here's an example implementation:

function save(user) {
  // perform async task here
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log(`${user.name} Saved!`);
      resolve()
    }, 1500);
  });
}

const main = async () => {
    const users = [
        { name: 'Benny', age: 28, status: 'active' },
        { name: 'Claire', age: 28, status: 'active' }
    ]
    
    const newUsers = users.map(user => save(user));
  
    await Promise.all(newUsers);
    console.log("Created users!")
}

const run = async () => {
  await main()
  console.log("done")
}

run()

By using this approach, database calls will execute concurrently, speeding up the seeding process significantly. Instead of running operations sequentially (in order), they will occur simultaneously unless specifically required for your use case.

Answer №2

One of my colleagues suggested the following solution:

const database = require('../database')
const Person = require('../models/person')

database.on('error', console.error.bind(console, 'Error connecting to MongoDB:'))

const initiate = async () => {
    const people = [
        new Person({ name: 'Alice', age: 30, status: 'active' }),
        new Person({ name: 'Bob', age: 35, status: 'inactive' })
    ]
    const addNewPeople = async () => {
        await Promise.all(people.map(async (person) => {
            await person.save()
        }))
    }
    await addNewPeople()
    console.log("People added successfully!")
}

const execute = async () => {
    await initiate()
    process.exit()
}

execute()

Answer №3

Here is the solution I came up with - any tips on how to make it better?

const db = require('../db')
const User = require('../models/user')

db.on('error', console.error.bind(console, 'MongoDB connection error:'))

const main = async () => {
    const users = [
        { name: 'Benny', age: 28, status: 'active' },
        { name: 'Claire', age: 28, status: 'active' }
    ]

    await User.insertMany(users)
    console.log("Users have been added!")
}

const run = async () => {
    await main()
    db.close()
}

run()

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

Trigger Element Upon Click

Forgive me in advance for the lack of quality in this question, but I'll proceed anyway: All I want is for an element to slide open when clicked with a mouse! That's all! More specifically, I am looking for a single menu item that, upon clickin ...

Determine the exact width of text without rounding in Javascript

I'm facing an issue with a div element that I'm manipulating using Javascript to change its position. The problem is that it's rounding off incorrectly. #hi{ background-color: blue; width: 2px; height: 10px; position: absolu ...

Difficulty in modifying a global variable within an event handler

I am working on an ionic4 app that includes a button. The goal is to display the accelerometer alpha value when the button is pressed. However, I am encountering an issue where the event handler invoked by the event listener does not seem to update the g ...

Using Puppeteer to Retrieve a List of Items with Identical Selectors

Issue: I am currently working on developing an end-to-end regression test for an EmberJS solution using NodeJS/CucumberJS/Puppeteer. However, I have encountered a challenge that I need help with. Challenge: The problem lies in selecting (page.click) and ...

When executing code in React JS, I encountered no errors, but the output did not match my expectations

I am facing a challenge with running the Hello World program in React JS using webpack. Attached below is the project structure for reference: https://i.stack.imgur.com/tQXeK.png Upon executing the npm run dev command in the CLI, the browser launches bu ...

Issue with custom video plugin functionality on Internet Explorer browser

I designed a custom video plugin that allows me to use shortcodes for videos with a unique format. I implemented a code snippet from jsfiddle to create a prominent play button, which functions smoothly across all browsers except for Internet Explorer. Desp ...

"Connection issue: SpringBoot application in Docker unable to reach Mongo database running in a

I created a Spring Boot Application using MongoDB on brew services. Initially, connecting to the database was as simple as updating the application.properties file in Spring Boot with: spring.data.mongodb.uri=mongodb://localhost:27017/db When I tried cha ...

What is the best way to animate an element to move to another element and then return to its original position when clicked using JQuery?

Goal How can we implement a method to move item 3 to another container? If clicked again, how can we return the item to its previous position? This functionality needs to be applicable to all items. Javascript $('#item3').click(function(){ ...

Axios - retrieving merchandise

I have created an endpoint that retrieves all product information in JSON format. I am attempting to display this data on my index.html page using Axios, but I am encountering difficulties with getting the data correctly. This is my first time working with ...

What is the method for renaming or aliasing fields when retrieving data from MongoDB using a query with the MongoDB-Node.JS native driver?

Consider this code snippet for fetching data from a local MongoDB server: var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require( ...

JavaScript believes that the function is not defined, despite its clear existence

This question pertains to an issue regarding the recognition of Bookshelf.js model function as a function. The error message "Function is undefined, Bookshelf.js model function is not being recognized as a function" arises when trying to POST to the login ...

I'm currently working on incorporating a rating system into my Vue.js project, but I am struggling to successfully pass the rating values

After carefully reviewing the documentation, I implemented the code below. While I am successfully retrieving data for enquiryDesc, I am encountering null values for rating. Despite trying various troubleshooting steps, the issue with null values persists. ...

Is it possible for a div with fixed position to still have scrolling functionality

My fixed positioned div (#stoerer) appears to be moving while scrolling, although it is just an optical illusion. Check out this visual explanation: view gif for clarification Below is the code snippet in question: <div id="stoerer"> <button ...

Update the value of a table cell with jQuery

I need assistance with changing the value of a td when a specific button is clicked. I have attempted various methods but none seem to be working. Ideally, I want the column to display only USD values when the "Show USD" button is clicked, and display on ...

Watch an object with AngularJS's $scope and detect and respond only to changes in its property values

Currently, I am monitoring scope changes using a simple watch like this: $scope.$watch('myObject', function(newValue, oldValue) { if (newValue !== oldValue) { return newValue; } }, true); In this case, myObject is an ordinary ob ...

Error functions in Angular HTTP Interceptor are not being triggered

I followed the example code for an interceptor from the Angular HTTP documentation, but I am having trouble getting the "requestError" and "responseError" functions to trigger. The "request" and "response" functions are working as expected. myApp.config([ ...

"Troubleshooting problem with graphql and express related to syntax and pre-compilation

Hey there, I'm currently trying to create a booking system by following a tutorial video. You can check out the video here The issue I'm facing is that even though my code is identical to the one in the tutorial, it's not working and I&apos ...

Incorporating AWS Sagemaker with MongoDB and Lambda

Seeking advice from experienced aws Sagemaker users. I'm a beginner and would appreciate any assistance. I've developed a basic time series project in a Sagemaker notebook, training the model on CSV file data with successful results. The datase ...

Searching and Sorting through JSON Data in React Native

I am currently expanding my knowledge in React Native and experimenting with filtering a JSON data set on a screen. My goal is to display only the filtered results on the screen. Would it be advisable for me to create a new component called FilteredTicket? ...

Using Highcharts to showcase a marker icon for a specific value

I am looking to add individual markers to my Highcharts graph. I want the outcome to resemble the example here: http://jsfiddle.net/m1mqv4z2/ { x: Date.UTC(2014, 6, 31) y: 26.5, marker: { symbol: 'u ...