DEV Community

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

Posted on

4

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.

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay