DEV Community

Cover image for What is ref in mongoose.js
Jahid Mridha
Jahid Mridha

Posted on

What is ref in mongoose.js

In Mongoose, a 'ref' is a property of a schema type that specifies the MongoDB collection in which the referenced documents live. It is used to create a "relationship" between two or more collections in a MongoDB database.

For example, suppose you have two collections in your MongoDB database: "users" and "posts". If you want to associate each "post" document with the "user" who wrote it, you can do so by using the 'ref' property in your Mongoose schema.

Here is an example of how you might use the 'ref' property in a Mongoose schema to create a relationship between the "users" and "posts" collections:

const userSchema = new mongoose.Schema({
  name: String,
  email: String
});

const postSchema = new mongoose.Schema({
  title: String,
  body: String,
  author: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }
});
Enter fullscreen mode Exit fullscreen mode

In this example, the 'author' field of the "post" schema is an 'ObjectId' that references a document in the "users" collection. The 'ref' property specifies that the 'author' field is a reference to a document in the "users" collection.

You can then use the 'populate()' method to populate the 'author' field with the actual user document, like this:

Post.find().populate('author').exec((err, posts) => {
  // `posts` is an array of post documents with the associated user documents
  // embedded in the `author` field
});
Enter fullscreen mode Exit fullscreen mode

I hope this helps! Let me know if you have any questions.

Top comments (0)