0

I am writing a code in which I want my _id to be started from 1 and should be incremented. And it has to be the reference to other collections as well. Now how can I change my objectId to a number and how to let the mongo db know that it is a primary key? How to implement a custom object ID which starts from 1 and increments as well in MongoDB using mongoose?

autoIncrement.initialize(mongoose);
var districtSchema=new Schema({
            _id             : {type: Schema.Types.Number, unique: true},
            district_name   : {type: String, unique: true},
            cities          : [{type: Schema.Types.Number, ref:'City'}]
        },
        {timestamps:{createdAt:'created_at',updatedAt:'updated_at'}});

districtSchema.plugin(autoIncrement.plugin, {model:'District',field:'_id',startAt:100,incrementBy:1});
var District=mongoose.model('District',districtSchema);
Aravind
  • 424
  • 3
  • 19
  • Is it usefull ? https://stackoverflow.com/questions/41444213/how-do-i-increment-a-number-value-in-mongoose – BENARD Patrick Jul 02 '19 at 08:53
  • No. What I've asked is, I am storing the _id fields like starting from 1 and made it auto-incremented, as per my requirements. Now when I am trying to join 2 collections using populate(), I couldn't do that as I am not storing _id as ObjectIds. So they are not working as Primary Keys. So the question is, how could I make them as Primary keys? Auto-incrementing is working well. – Aravind Jul 02 '19 at 11:15

0 Answers0