I had an opportunity to explain mongoose.Schema type: ObjectId, so here’s that content.
Q) I don’t understand the value of the type property highlighted in red in mongoose.Schema… Other objects have String or Number as values, but the user type property has a unique ID? which I don’t quite understand.
A) To give a rough answer first, ObjectId is the id of a MongoDB document, and in this case it defines a field that stores the user._id (ObjectId) of the ProfileSchema’s related ref.
I’ll explain this step by step below.
The ObjectId stored in ProfileSchema.user is the _id of the user document, called the primary key. The _id stores an ObjectId.
For ObjectId generation rules, please refer to the following article:
mongodbのObjectIdの生成規則 - としたにあんの左脳
For the question “What is a primary key?”, please read this:
主キー (primary key)とは|「分かりそう」で「分からない」でも「分かった」気になれるIT用語辞典
Note that an _id field has been added to the data you inserted. All documents must have a unique _id field. This means you either generate an ObjectID type value yourself or have MongoDB generate it. In most cases, you'll want MongoDB to generate it.Source: MongoDBの薄い本
Mongoose ref defines DB relations, and I think the following article is easy to understand:
RDB脳でもできた、mongooseを使ってmongodbでリレーションとjoinっぽいこと | I am mitsuruog
Besides expressing relations between MongoDB collections, I think the benefit of ref is that you can retrieve related documents together when finding.
The following article has sample code and execution results, so checking it together will help you visualize it better:
That’s all from the Gemba.