Skip to content
Related Articles

Related Articles

How does Query.prototype.cast() work in Mongoose ?

Improve Article
Save Article
  • Last Updated : 12 Mar, 2021
Improve Article
Save Article

The Query.prototype.cast() function casts this query to the schema of the model. And if the obj is present, then it is casted instead of this query.
Syntax: 
 

Query.prototype.cast()

Parameters: This function has one parameter i.e. the model to cast and if not set, then the default is this.model.
Return Value: This function returns Query Object.

Installing mongoose : 

npm install mongoose

After installing the mongoose module, you can check your mongoose version in command prompt using the command. 

npm mongoose --version

After that, you can just create a folder and add a file for example, index.js as shown below.

Example 1:

index.js




const mongoose = require('mongoose');
  
// Database connection
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
});
  
// User model
const User = mongoose.model('User', { 
    name: { type: String },
    age: { type: Number }
});
  
const query = User.find()
var res = query.cast();
  
console.log("Casted to self:", res)

The project structure will look like this:

Run index.js file using below command: 

node index.js

Output: 

Casted to self: {}

Example 2:

index.js




const express = require('express');
const mongoose = require('mongoose');
const app = express()
  
// Database connection
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
});
  
// User model
const User = mongoose.model('User', { 
    name: { type: String },
    age: { type: Number }
});
  
const query = User.find()
var res = query.cast();
  
console.log("Self Casting:", res)
  
app.listen(3000, function(error ){
    if(error) console.log(error)
    console.log("Server listening on PORT 3000")
})

The project structure will look like this:

Run index.js file using below command: 

node index.js

Output: 

Server listening on PORT 3000
Self Casting: {}

Reference: https://mongoosejs.com/docs/api/query.html#query_Query-cast


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!