unsafe_where_true
unsafe_where_true

Reputation: 6300

mongodb: how to automatically generate an id to a newly created object?

I am creating a new object with mongoose. How to automatically assign an ID to that object?

This is what I have so far (watch out: coffeescript):

ObjectSchema = new Schema({
   #some other properties
   id: { type: Schema.ObjectId, required: true}
})

This is how I create it:

obj = new Object()
#assign a couple of properties
obj.save( (err) ->
   if err?
     console.log(err)
   else
     console.log("successfully saved")
)

which gives me this error:

ValidationError: Path `id` is required

Upvotes: 0

Views: 3311

Answers (3)

Dineshaws
Dineshaws

Reputation: 2083

You can also manage ObjectId in your own field of document, I have attached some code of snippet in which 'id' is customized field of dummy doucment

var ObjectID = require('mongodb').ObjectID

var dummy_record = {id: new mongo.ObjectID(),  created: new Date()};

db.collection('dummy').insert(dummy_record, {w: 1}, function(err, records) {
if (err) {
    // handle error here
} else {
   // do whatever you want, after insertion of record
} 
});

Note:- As previous answers of this question, '_id' is pre-defined field of document which is auto filled by default, no extra work require for same, but if you want to change field name or want some other filed like 'id' you can use above lines of code for same.

Thanks

Upvotes: 1

Don't declare any id field in your schema, and after saving, your object will have an _id autogenerated field.

Upvotes: 3

Petrus Prinsloo
Petrus Prinsloo

Reputation: 294

It gets automaticly created when its not specified on a insert

Only specify the other properties of your document

Upvotes: 1

Related Questions