1

I have an old codebase where parse-server is used with MongoDB. And it generate _id as a string instead of ObjectId. I want to replace parse-server to mongoose. Is it possible to generate string ids with mongoose? Currently I don't want to change existing ids. What you can suggest? Thanks

2 Answers2

0

One of the oldest function known to mankind in programming world .toString() can do the job for you, with mongoose > 5.4.0 you can convert any ObjectID to string using .toString().

You can read about it here

Shivam
  • 3,514
  • 2
  • 13
  • 27
0

Extracted from Parse-server code (https://github.com/parse-community/parse-server/blob/2b26cc043e6a06f9c61ea17227a3f88e69310d14/src/cryptoUtils.js#L16)

//
// Note: to simplify implementation, the result has slight modulo bias,
// because chars length of 62 doesn't divide the number of all bytes
// (256) evenly. Such bias is acceptable for most cases when the output
// length is long enough and doesn't need to be uniform.
export function randomString(size: number): string {
  if (size === 0) {
    throw new Error('Zero-length randomString is useless.');
  }
  const chars =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789';
  let objectId = '';
  const bytes = randomBytes(size);
  for (let i = 0; i < bytes.length; ++i) {
    objectId += chars[bytes.readUInt8(i) % chars.length];
  }
  return objectId;
}

// Returns a new random alphanumeric string suitable for object ID.
export function newObjectId(size: number = 10): string {
  return randomString(size);
} ```