Mongoose Query.prototype.model API
The Mongoose Query API.prototype.model property of the Mongoose API is used on the Query objects. It allows us to verify the model with which the current query is associated with. Let us understand model property using an example.
Syntax:
query.model;
Parameters: This property does not accept any parameter.
Return Value: This property returns the model name on which the query is operating.
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 are illustrating the functionality of model property, by accessing it on the query object.
Filename: app.js
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 query = Customer.find(); const res = query.model console.log(res); |
Step to run the program: To run the application execute the below command from the root directory of the project:
node app.js
Output:
Model { Customer }
Example 2: In this example, we are illustrating the functionality of model property, by accessing it on the query object. At the end, we are comparing the value return by model property with the Customer model.
Filename: app.js
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 query = Customer.find(); const output = query.model === Customer; console.log(output); |
Step to run the program: To run the application execute the below command from the root directory of the project:
node app.js
Output:
true
Reference: https://mongoosejs.com/docs/api/query.html#query_Query-model
Please Login to comment...