Skip to content
Related Articles

Related Articles

How does Query.prototype.$where() work in Mongoose?

Improve Article
Save Article
  • Last Updated : 28 Oct, 2022
Improve Article
Save Article

The Query.prototype.$where() specifies a JavaScript function or expression to pass to MongoDB’s query system. Using this, the where condition can be customized according to the need of the user.

Syntax:

Query.prototype.$where()

Parameters: This function has one parameter js i.e. JavaScript string or function.
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.

Database: The sample database used here is shown below: 
 

Project Structure: The project structure will look like this: 
 

Example 1:

index.js


const mongoose = require('mongoose');

// Database connection
mongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
});

// User model
const User = mongoose.model('User', { 
    name: { type: String },
    age: { type: Number }
});

const query = User.find(); 
query.collection(User.collection);

query.$where(function () {
    if (this.age < 100) return true;
    else return false;
})

query.where('age').gte(1).exec(function(error, result) {
    if (error) {
        console.log(error)
    } else {
        console.log(result)
    }
});

Run index.js file using below command: 

node index.js

Output: 

[
  { _id: 5ebb9129a99bde77b2efb809, 
    name: 'Gourav', age: 10, __v: 0 },
  { _id: 5ebc3669a99bde77b2efb9ba, 
    name: 'Lalit', age: 25, __v: 0 }, 
  { _id: 5ebc367da99bde77b2efb9bf,
    name: 'Piyush', age: 5, __v: 0 }, 
  { _id: 5ebd345f5d2d8a3534b2f391,
    name: 'Manish', age: 34, __v: 0 } 
]

Example 2:

index.js


const mongoose = require('mongoose');

// Database connection
mongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
});

// User model
const User = mongoose.model('User', { 
    name: { type: String },
    age: { type: Number }
});

const query = User.find(); 
query.collection(User.collection);

query.$where(function () {
    if (this.age < 100) return false;
    else return true;
})

query.where('age').gte(1).exec(function(error, result) {
    if (error) {
        console.log(error)
    } else {
        console.log(result)
    }
});

Run index.js file using below command: 

node index.js

Output: 

[]

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

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!