skip to Main Content

Below is my code to save data in a mongodb

const mongoose = require('mongoose')

const sampleschema = new mongoose.Schema(
    {
        name:{
            type:String
        },
        age:{
            type:Number
        }
    },
    {collection :"Sample_collection"}
)
const samplemodel = mongoose.model('sample_coll',sampleschema)


const add = async () =>
{
    const samplerecord = new samplemodel({    
        name:'FFFF',
        age:26
    })
try
{   
    await  samplerecord.save()                 // Line A
await  samplemodel.create(samplerecord)    // Line B
   
    console.log("Style")
}
catch(e)
{
    console.log("This is error",e)
}
}

Now I have written both Line A & Line B . Now , I think two records shall be created in my database with same value except different _id , however I am seeing that only one record is being created. Why is it happening so ? Even if I change the order of line A and line B same issue persists. What is the issue because of which only one record is being created ?

2

Answers


  1. await samplerecord.save(); it gives the data which is saved in database as it is promise based so, await/(then-catch) is required .

    const mongoose = require("mongoose");
    
    const sampleschema = new mongoose.Schema(
      {
        name: {
          type: String,
        },
        age: {
          type: Number,
        },
      },
      { collection: "Sample_collection" }
    );
    const samplemodel = mongoose.model("sample_coll", sampleschema);
    
    const add = async () => {
      try {
        const samplerecord = new samplemodel({
          name: "FFFF",
          age: 26,
        });
    
        //.save() method returns the object that it saves in database
        let result = await samplerecord.save(); // Line A
        //.create() does not need .save() method
        await samplemodel.create(result); // Line B
    
        console.log("Style");
      } catch (e) {
        console.log("This is error", e);
      }
    };
    Login or Signup to reply.
  2. The reason only one document is stored in the database is because when you create a new instance of the model here:

    const samplerecord = new samplemodel({    
        name:'FFFF',
        age:26
    });
    

    mongoose actually assigns an _id property to samplerecord before it’s even saved. That means by the time you pass samplerecord to the await samplemodel.create(samplerecord) function on Line B, that ObjectId already exists in the database because you called the save() method on samplerecord on Line A so you can’t have two with the same _id.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search