I am still a beginner in mongo db. So I want to add id
attribute to my data objects. Right now, when I ran my code below, it says 'document must have an _id before saving'. I tried to add _id
in the Schema along with name
and number
properties like this,
const personSchema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: String,
number: Number,
})
I also tried creating a variable to generate id const objectId = ObjectId()
and add the id
attribute to each one in my data objects, id: objectId
but this too still not working. Other things that I've tried is creating a new object like this,
const person2 = new Persons({
name: 'Aidil',
number: '321321321',
})
But this is not practical with few data objects since I would have to call save
to each new object. How do I fix this ? The following are my code,
const personSchema = new mongoose.Schema({
name: String,
number: Number,
})
const Persons = mongoose.model('Person', personSchema)
const person = new Persons(
{
name: 'Arto Hellas',
number: '040123456',
},
{
name: 'Jabss',
number: '1223132133',
})
person.save().then( result => {
console.log('person saved!')
mongoose.connection.close()
})