YulePale
YulePale

Reputation: 7666

How to define an objectId type in mongoose 6.0.0^

I am seeing many answers saying that the correct way to define an objectId type in a mongoose schema is like:

type: mongoose.Schema.Types.ObjectId

But from the mongoose docs they show that you can define an objectId type like so:

const carSchema = new mongoose.Schema({ driver: mongoose.ObjectId });

Is there something I am missing? What is the correct way to define an objectId type? Are both methods correct or one is outdated?

Upvotes: 0

Views: 144

Answers (1)

Alex Blex
Alex Blex

Reputation: 37018

Both of these roads lead to Rome, there is no single "correct" way.

The type is defined in https://github.com/Automattic/mongoose/blob/master/lib/schema/index.js#L24 as

exports.ObjectId = require('./objectid');

The rest are the pointers to this export. Some are shorter, some are longer unless you use them in the context.

The mongoose.Schema.Types.ObjectId comes from there: https://github.com/Automattic/mongoose/blob/master/lib/schema.js

Schema.Types = MongooseTypes = require('./schema/index');

mongoose.ObjectId comes from https://github.com/Automattic/mongoose/blob/master/lib/index.js#L940

Mongoose.prototype.ObjectId = SchemaTypes.ObjectId;

Upvotes: 1

Related Questions