Open In App

Mongoose SchemaType.prototype.ref() API

Last Updated : 07 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The MongooseSchemaType.ref() method of the Mongoose API is used to build relationships between two Schema based on Objects Id’s. We can set the reference of a modal using Modal Name, Modal Class, Function that returns Modal Name, and Function that returns Modal Class. We can access the ref() method on an Object of Schema.

Syntax:

MongooseSchemaType.ref()

Parameters: The MongooseSchemaType.ref() method accepts one parameter i.e Modal Name or Modal Class:

  • ref: It refers to the name of Modal, Modal class, or Function that returns Modal Name or Modal Class.

Return Value: The MongooseSchemaType.ref() function returns a reference of SchemaType. 

Setting up Node.js application:

Step 1: Create a Node.js application using the following command:

npm init

Step 2: After creating the NodeJS application, Install the required module using the following command:

npm install mongoose

Project Structure: The project structure will look like this

 

Example 1: In this example, we have established a database connection using mongoose and defined two models. First, userSchema, has two columns or fields “name”, and “age” and Second, studentSchema has three columns or fields including ref “rollNumber”, “address”, and “user”. In the end, we are using ref() to reference the User Modal to Student Modal. We are setting the “User” modal reference on the “user” field of Student Modal or Student Schema.

app.js:  Write down the below code in the app.js file:

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const userSchema = new mongoose.Schema({
    name: String,
    age: Number,
});
  
// Defining userSchema model
const User = mongoose.model("User", userSchema);
  
const studentSchema = new mongoose.Schema({
    rollNumber: Number,
    Address: String,
    user: mongoose.SchemaTypes.ObjectId
})
  
// Defining studentSchema model
const Student = mongoose.model("Student", studentSchema);
  
// Setting modal name as String
studentSchema.path('user').ref('User');
  
console.log(studentSchema.paths.user)


Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

ObjectId {
  path: 'user',

  instance: 'ObjectID',
  validators: [],
  getters: [],
  setters: [],
  _presplitPath: [ 'user' ],
  options: SchemaObjectIdOptions {
    type: [Function: ObjectId] {
      schemaName: 'ObjectId',
      defaultOptions: {},
      get: [Function (anonymous)],
      set: [Function: set],
      _checkRequired: [Function (anonymous)],
      _cast: [Function: castObjectId],
      cast: [Function: cast],
      _defaultCaster: [Function (anonymous)],
      checkRequired: [Function (anonymous)]
    },
    ref: 'User'
  },
  _index: null,
  [Symbol(mongoose#schemaType)]: true
}

Example 2: In this example, we set the reference modal while creating the student schema. We can do this by specifying “user” field in studentSchema as an Object of the “type” and “ref” keys.

app.js: Write down the below code in the app.js file:

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
{
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const userSchema = new mongoose.Schema({
    name: String,
    age: Number,
});
  
// Defining userSchema model
const User = mongoose.model("User", userSchema);
  
// Defining ref while creating student Schema
const studentSchema = new mongoose.Schema(
{
    rollNumber: Number,
    Address: String,
    user: { type: mongoose.SchemaTypes.ObjectId, ref: User }
})
  
// Defining studentSchema model
const Student = mongoose.model("Student", studentSchema);
  
// Setting modal name as String
studentSchema.path('user').ref('User');
  
console.log(studentSchema.paths.user)


Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

ObjectId {
 path: 'user',
 instance: 'ObjectID',
 validators: [],
 getters: [],
 setters: [],
 _presplitPath: [ 'user' ],      
 options: SchemaObjectIdOptions {
   type: [Function: ObjectId] {  
     schemaName: 'ObjectId',     
     defaultOptions: {},
     get: [Function (anonymous)],
     set: [Function: set],
     _checkRequired: [Function (anonymous)],
     _cast: [Function: castObjectId],
     cast: [Function: cast],
     _defaultCaster: [Function (anonymous)],
     checkRequired: [Function (anonymous)]
   },
   ref: 'User'
 },
 _index: null,
 [Symbol(mongoose#schemaType)]: true
}

Reference: https://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-ref



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads