Using UUIDs in mongoose for ObjectID references Using UUIDs in mongoose for ObjectID references express express

Using UUIDs in mongoose for ObjectID references


You can still use populate() with _id values of types besides ObjectID, but you do need to use the same type in the reference definition.

So your trackPassSchema would need to change to:

var trackPassSchema = new Schema({    _id: { type: String, default: function genUUID() {        return uuid.v1()    }},    vehicle: [        {type: String, required: true, ref: 'Vehicle'}    ]});

As Adam notes in the comments, you could simplify your default value to:

var trackPassSchema = new Schema({    _id: { type: String, default: uuid.v1 },    vehicle: [        {type: String, required: true, ref: 'Vehicle'}    ]});


Both JohnnyHK and Adam C answers are correct. But if you're using uuid in schema for an array of objects, it is good to use it like this

var trackPassSchema = new Schema({_id: { type: String, default: () => uuid.v1 },vehicle: [    {type: String, required: true, ref: 'Vehicle'}]

});

Because, in one such scenario when i tried using like this _id: { type: String, default: () => uuid.v1 } multiple objects of the array had the same id.

It is not possible in this case as _id is unique field, but it can happen when you are using with fields that aren't unique.