Vahan
Vahan

Reputation: 58

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

Upvotes: 2

Views: 113

Answers (1)

Gabriel Lupu
Gabriel Lupu

Reputation: 1447

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.

Upvotes: 1

Related Questions