2

I was thinking of using cuid (https://www.npmjs.com/package/cuid) to replace mongoose's naturally generated objectids, so that _id in my model would get a cuid rather than a generated one.

Questions:

  1. How do you achieve this
  2. Are there any side effects
  3. How would this affect population??

Is 1 as simple as:

import mongoose from 'mongoose';
import cuid from 'cuid';

const Schema = mongoose.Schema;

export const departmentSchema = new Schema({
  _id: { type: 'String', default: cuid(), required: true },
  name: { type: 'String', required: true },
  sector: { type: 'String', required: true },
});

??

Thanks

user1775718
  • 1,499
  • 2
  • 19
  • 32

1 Answers1

2

I've had success using the following to use a CUID instead of _id:

import mongoose from 'mongoose';
import cuid from 'cuid';

const gymSchema = new Schema({
  _id: { type: 'String', required: true, default: cuid },
}):

The difference being that I simply pass the function, whereas you call the function. I made that mistake at first...

I can confirm that population works as expected, but the question that I can't answer is whether there are any side effects. And possibly, more importantly, why you would want to do this. mern.io uses CUIDs instead of the ObjectId, but they do it awkwardly in another field. I don't know why the ObjectIds aren't appropriate. Anyone?

shankie_san
  • 181
  • 1
  • 12