According to schema types docs
A SchemaType is different from a type. In other words, mongoose.ObjectId !== mongoose.Types.ObjectId. A SchemaType is just a configuration object for Mongoose. An instance of the mongoose.ObjectId SchemaType doesn't actually create MongoDB ObjectIds, it is just a configuration for a path in a schema.
Also into docs:
You can think of a Mongoose schema as the configuration object for a Mongoose model. A SchemaType is then a configuration object for an individual property. A SchemaType says what type a given path should have, whether it has any getters/setters, and what values are valid for that path.
So, mongoose.Types.ObjectId
is a "mongoose object" while mongoose.ObjectId
is a "mongodb object".
Edit to answer the comments.
To the first question, for me is: Yes. As a developer that use mongoose I only use mongoose functions. That implies use mongoose.Types.ObjectId
instead of mongoose.ObjectId
.
Also if you try to do mongoose.ObjectId()
you will get a warning 'To create a new ObjectId please try Mongoose.Types.ObjectId
instead of using Mongoose.Schema.ObjectId
'
About the second question, if I've understood correctly, yes too. You can check this.
Create a new schema and do:
const MongooseModel = new mongoose.Schema({_id: mongoose.Types.ObjectId})
MongooseModel.path('_id') instanceof mongoose.Schema.ObjectId // true
MongooseModel.path('_id') instanceof mongoose.SchemaTypes.ObjectId // true
MongooseModel.path('_id') instanceof mongoose.Schema.Types.ObjectId // true
MongooseModel.path('_id') instanceof mongoose.ObjectId // true
MongooseModel.path('_id').instance // ObjectID
MongooseModel.path('_id') instanceof mongoose.Types.ObjectId // false
mongoose.Schema.ObjectId instanceof mongoose.Types.ObjectId // false
Your schema _id
is created via mongoose.Types
and is instance of mongoose.ObjectId
. Also is not an instance of the type, as explained into docs "A SchemaType is different from a type".
The _id
generated is an instance of the ObjectID
but is not an instance of the "parent" who generates the value.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…