Open In App

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

Last Updated : 12 Mar, 2021
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

The Query.prototype.box() is used to specify a $box condition. When this function is used, the $geoWithin returns documents based on the grid coordinates.
Syntax: 
 

Query.prototype.box()


Parameters: This function has one array object parameter which has upper-left co0rdinates and upper-right coordinates.
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
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(); 

var lower_left = [23, -71]
var upper_right= [12, 11]

query.where('loc').within().box(lower_left, upper_right)
query.box({ ll : lower_left, ur : upper_right})

console.log("Geo Location within: ",
    query._conditions.loc.$geoWithin)

The project structure will look like this:

Run index.js file using below command: 

node index.js


Output: 

Geo Location within:  { '$box': [ [ 23, -71 ], [ 12, 11 ] ] }


Example 2:

index.js
const express = require('express');
const mongoose = require('mongoose');
const app = express()

// 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(); 

var lower_left = [21, -33]
var upper_right= [-6, 32]

query.where('loc').within().box(lower_left, upper_right)
query.box({ ll : lower_left, ur : upper_right})

console.log("Geo Location is: ",
    query._conditions.loc.$geoWithin)

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
Geo Location is:  { '$box': [ [ 21, -33 ], [ -6, 32 ] ] }

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


Next Article

Similar Reads