如何在 mongoDB 中使用其他类型的 ID

How to use another type of id in mongoDB

任务是将 mongoDb 中的默认唯一 _id 更改为具有那种视图 0000100002 的自动递增 id,我只做过这样的自动递增1, 2 , 但不确定这种方式是否正确

这是我的自增代码:

//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();

我的代码结果照片

MongoDB 不会让您保存类型为 number 且以一串零开头的道具。

我会将 id 保存为字符串类型,并在使用它时将其转换为数字,然后将其作为字符串保存回 mongoDB(如果确实需要)。

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)

总而言之,将您的 ID 保存为带有额外零的字符串,在使用它们时将它们转换为数字,然后再保存到数据库中返回字符串。