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
await samplerecord.save(); it gives the data which is saved in database as it is promise based so, await/(then-catch) is required .
The reason only one document is stored in the database is because when you create a new instance of the model here:
mongoose actually assigns an
_id
property tosamplerecord
before it’s even saved. That means by the time you passsamplerecord
to theawait samplemodel.create(samplerecord)
function on Line B, thatObjectId
already exists in the database because you called thesave()
method onsamplerecord
on Line A so you can’t have two with the same_id
.