DEV Community

Cover image for What is ref in mongoose.js
Ifeanyi Chima
Ifeanyi Chima

Posted on • Edited on

What is ref in mongoose.js

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.

Image description

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"]
},

})



Enter fullscreen mode Exit fullscreen mode

goalModel.js



const goalSchema = schema({

user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true
},

text: {
type: String
}

})

Enter fullscreen mode Exit fullscreen mode




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.

Buy Me A Coffee

Thank you, please follow me

HTML GitHub

Top comments (1)

Collapse
 
skwiddevz profile image
T Parker

Thank you, this helps as I was trying to call the USER as a schema array..
Does this automatically find the userSchema ID?