when should I use object id ? instead of using just String
car:{type:mongoose.Schema.Types.ObjectID,ref:'cars'}
user:{type:mongoose.Schema.Types.ObjectID,ref:'users'},
instead of just using
type:String
? untill now it was always
type:string
CodePudding user response:
With mongoose schema definition you don't need to use 'mongoose.Schema.Types.ObjectID' you can simply pass :
{
...
entity: {
type: 'ObjectId',
ref: 'entity'
}
...
}
As defined here ObjectId is the default generated _id unique value of document storing timestamp and counter.
for a simple answer to 'when should I use object id ?' : when it refers to another document that use ObjectId
CodePudding user response:
You are defining a relation between specific collections. Basically be defining
user:{type:mongoose.Schema.Types.ObjectID,ref:'users'},
in a schema, you are telling mongoose, that theuser
attribute is not just a plain string, but a reference to the _id of a document inusers
collection. You can then (e.g.) use functions like.populate('user')
to perform a lookup on this previously defined relation.You are restricting what can be stored in this attribute. If you define this attribute as a plain string, you can store everything you want in it without an error being raised, even if it is no valid _id of a foreign document. Defining it as an ObjectId helps to prevent errors, because only valid IDs can be stored in this attribute.