Search code examples
mongodbmongoosemongoose-schema

How to create human readable mongodb records id?


Suppose i want to create a mongodb records, an _id is created automatically. But i want to create this records as an id : 1 and the more records i created, the id will be increased automatically like 2 , 3 ,4


Solution

  • One way you can do this by creating an id Integer object in the MongoDB model and increase it, whenever you create a new record

    const bootcamp = await Bootcamp.find();
    const length = bootcamp.length+1
    req.body.id = length
    await Bootcamp.create(req.body);
    

    and then save id along with a new record and you can find your record like that

    const result = await Bootcamp.findOne({ id: req.body.id})  
    

    But you cannot edit the _id provide by MongoDB