Search code examples
javascriptmongodbmongoosenestjsmongoose-schema

How to use another type of id in mongoDB


The task is to change default unique _id in mongoDb to autoincremented id with that kind of view 00001, 00002, I have done only autoincrement like that 1, 2 , but not sure is that way right or no

here is my autoincrement code:

//here we sort by id and found the last added product
const lastProd = await this.productModel
      .findOne()
      .sort({ _id: 'desc' })
      .exec();
 
 
    const newProduct = new this.productModel({
    //if last prod is not null, do increment
      _id: lastProd ? lastProd._id + 1 : 0,
      title,
      description: desc,
      price,
      image:image.filename,
    });
    const result = await newProduct.save();

photo of result of my code

enter image description here


Solution

  • MongoDB will not let you save prop with type number that starts with a bunch of zeros.

    I would save the id as type string & when working with it convert it to a number, and saving it back in mongoDB as a string (if really necessary).

    const parseIdFromNumber = id => {
      if (id < 10) return `000${id}`;
      if (id < 100) return `00${id}`;
      if (id < 1000) return `0${id}`;
    }
    
    const a = parseIdFromNumber(4);
    const b = parseIdFromNumber(22);
    const c = parseIdFromNumber(233);
    
    // save to db
    console.log(a, b, c)
    // converting string ids to numbers
    console.log(+a, +b, +c)

    In conclusion save your ids as strings with the extra zeros, when working with them convert them to numbers and before saving into DB back to strings.