0

Is there a way to generate an ID for a new document?

Something like

var newID = mongoose.Types.ObjectId();

// some random code that may involve db operations.

db.Model.create({_id: newID, otherProperties: {}})

When I write something like this, actual ID of the created document is always slightly larger than the newID. Is there anyway to use the newID exactly?

Rizvan
  • 521
  • 1
  • 7
  • 20
Zhen Liu
  • 7,550
  • 14
  • 53
  • 96

1 Answers1

0

You should not create ID attribute for mongodb documents, It will automatically generate an ID attribute to all documents when we create them.

e.x

db.users.insert({name:'kasun',email:'kasun@gmail',address:'2street,colombo'})

this will crete an attribute called _id for the document of kasun.It is unique.Therefore don't set id attribute manually.