Open In App

Mongoose Schema API Connection.prototype.modelNames()

Improve
Improve
Like Article
Like
Save
Share
Report

The Connection.prototype.modelNames() method of the Mongoose API is used on the Connection object. It allows us to get information about all the models that have been created using a particular connection object. 

Syntax:

connection.modelNames( );
  • Parameters: This method does not accept any parameter.
  • Return Value: This method returns an array. Return array of model names created using particular connection object.

Setting up Node.js Mongoose Module:

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 will create a database connection using the createConnection() method and define userSchema on its object. In the end, we will fetch all the models we have defined for the con connection object using modelNames() method.

Filename: write down the below code in app.js file.

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
const con = mongoose.createConnection("mongodb://localhost:27017/geeksforgeeks", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
  
const userSchema = new mongoose.Schema({
  name: String,
  fixedDeposit: Number,
  interest: Number,
  tenure: {type:Number, default:6}
});
  
const User = con.model('User', userSchema);
  
console.log(con.modelNames());


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

node app.js

Output:

[ 'User' ]

Example 2: The below example illustrates the basic functionality of the Mongoose Connection modelNames() method.

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

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
  
const connectionObject = mongoose.createConnection(URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
  
const Customer = connectionObject.model('Customer', new mongoose.Schema({
  name: String,
  address: String,
  orderNumber: Number,
}));
  
const Student = connectionObject.model('Student', new mongoose.Schema({
  name: String,
  age: Number,
  rollNumber: Number
}));
  
const modelDetails = connectionObject.modelNames();
console.log(modelDetails);
console.log(modelDetails.length);


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

node app.js

Output:

[ 'Customer', 'Student' ]
2

Reference:- https://mongoosejs.com/docs/api/connection.html#connection_Connection-modelNames



Last Updated : 15 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads