When writing a Node.js
application with persistent storage such as MongoDB
, we would need to populate (fill) our database with information to store.
If you are a familiar with NOSQL
types of databases, you would know that we store informations in documents and collections.
When trying to populate your database, we create schemas. A schema dictates how the documents (objects) in our collection should look like.
Scenario
Let us say you are creating a To-do application and you want the goals (to-dos) to be associated with a particular user. You would create a schema for Users and a schema for goals. The question is, How do you attach the goals to a user.
Ref option
Now, you can reference documents in other collections. You can replace a specified path in a document with document(s) from other collection(s), this process is known as population
The ref
option is what tells mongoose.js
which model to use during population
.
Example
userModel.js
const userSchema = schema({
user: {
type: String
required: [true, "add a name"]
},
})
goalModel.js
const goalSchema = schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true
},
text: {
type: String
}
})
Explaination
In our goalModel
, it contains a user field which is set to type ObjetId
, and with the ref
option, we have told mongoose
to use the id from our userModel
to fill the user field in goalModel
during population.
This means all _id
we store in the user
field of goalModel
must be document _id
from the User Model.
Thank you, please follow me
Top comments (1)
Thank you, this helps as I was trying to call the USER as a schema array..
Does this automatically find the userSchema ID?