Open In App

Mongoose Document Model.prototype.collection API

Improve
Improve
Like Article
Like
Save
Share
Report

The Model.prototype.collection property of the Mongoose API is used to display collection-related information on any model. It showcases collections that are being used by models. Model.prototype.collection property is a read-only property, modification on this property will not work.

Syntax:

Model_Name.collection

Returns: The Model.prototype.collection property returns an object with the number of nested objects and properties.

 

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 model over userSchema, having two columns or fields “name” and “age”. In the end, we are using the collection property on the User model which will return the collection that is being used by the User model.

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

app.js




// Require mongoose module
const mongoose = require('mongoose');
  
// Set Up the Database connection
mongoose.connect(
    useNewUrlParser: true,
    useUnifiedTopology: true
})
  
const userSchema = new mongoose.Schema(
    { name: String, age: Number }
)
  
// Defining userSchema model
const User = mongoose.model('User', userSchema);
  
const output = User.collection
console.log(output)


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

node app.js

Output:

 

Example 2: In this example, We have established a database connection using mongoose and defined model over studentSchema, having four columns or fields “name”, “age”, “city”, and “state”. In the end, we are using the collection property on the Student model which will return the collection that is being used by the Student model.

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

app.js




// Require mongoose module
const mongoose = require('mongoose');
  
// Set Up the Database connection
mongoose.connect(
    useNewUrlParser: true,
    useUnifiedTopology: true
})
  
const studentSchema = new mongoose.Schema(
    { name: String, age: Number, city: String, state: String }
)
  
// Defining studentSchema model
const Student = mongoose.model('Student', studentSchema);
  
const output = Student.collection
console.log(output)


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

node app.js

Output:

 

Reference: https://mongoosejs.com/docs/api/model.html#model_Model-collection



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