0

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()
})
  • please show the errors log, your code looks good, need to understand your log errors – Tobok Sitanggang Mar 03 '23 at 12:53
  • Are you trying to create multiple persons with this code? ```js const person = new Persons( { name: 'Arto Hellas', number: '040123456', }, { name: 'Jabss', number: '1223132133', }) ``` – AveN7ers Mar 03 '23 at 13:11
  • I am sorry I think I am mistaken of how mongodb works. I think I would need to add each data object one by one since each time after I save it, it is stored in the mongo db. I also think this is how the data will be added in real projects ? I mean this is the practical way of adding data. but in any case, if I want to add the second data like in the code above ? is it possible ? correct me if I am wrong – Jabri Juhinin Mar 03 '23 at 13:33
  • @TobokSitanggang, if I were to add data object like in my code above, the error is 'document must have an _id before saving' – Jabri Juhinin Mar 03 '23 at 13:35
  • @Jabri Juhinin right, as @AveN7ers said, your put it wrong with the object. If you need to do `multiple insert`, please follow this link https://stackoverflow.com/a/75619230/9267467. Operation `save` is used to create only one data. for multiple insert, you will need `bulkwrite`. – Tobok Sitanggang Mar 03 '23 at 13:46

1 Answers1

0

Your problem probably stems from this code

const Persons = mongoose.model('Person', personSchema)

const person = new Persons(
{
  name: 'Arto Hellas',
  number: '040123456',
}, 
{
  name: 'Jabss',
  number: '1223132133',
})

According to the docs the second argument to the Schema constructor is an options object. You passed in another person object.

AveN7ers
  • 119
  • 1
  • 4