Home > Enterprise >  Data not getting added to mongodb
Data not getting added to mongodb

Time:09-24

I am new to mongodb and nodejs. I am trying to add some data to MongoDB but it's not getting updated in the database. Can someone help me figure out the issue? My code is as follows:

    for (i = 0; i < DataArray.length; i  ) {
        try {
           const newDoc = new Document(DataArray[i]);
           newDoc.save()
                 .then(() => logger.info("Data Added !!"))
                 .catch((err) => {
                      logger.error(err);
                      logger.info("Something went wrong");
                 });
        }
    }

The DataArray is a list of documents that need to be added to MongoDB. I am trying to take each data and add it to db. Document is the reference to the particular collection in db.

CodePudding user response:

In MongoDb Basic Flow is like this & Use Async-Await in your function.

Step 1: Define Schema in your file exp.

const userSchema = require('your schema path here');

Step 2: Put Values in Schema Object exp.

const user = new userSchema({username: 'darshanuraval', age: 23});

Step 3: Put this Save Function in Try Catch So that if any errors comes then we got that in catch. exp.

try {
    await user.save();
    res.send("inserted data");
} catch (err) {
    console.log(err);
}

CodePudding user response:

In other way Try this, Use Promise and Map function so it's works.

let obj = await Promise.all(DataArray.map(async function(mapData){
    let newDoc = new Document(mapData);
    await newDoc.save();
    return mapData;
}));

CodePudding user response:

You are running save in for loop, do this instead:

await Promise.all(
    DataArray.map(async (data) => {
        const newDoc = new Document(data);

        await newDoc.save();            
        logger.info("Data Added !!")
       
        return data;
    })
);

const allDocuments = await Document.find();
console.log("allDocuments", allDocuments);
  • Related