Skip to content
Related Articles

Related Articles

Improve Article

How does Query.prototype.geometry() works in Mongoose ?

  • Last Updated : 23 Jul, 2021

The Query.prototype.geometry() function is used to specify a $geometry condition. The geometry can be provided in an array which is passed as parameter.
 

Syntax:  

Query.prototype.geometry()

Parameters: This function has one object parameter which must contain a type property of string type and a coordinates property of array type. 
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

Database: The sample database used here is shown below.



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

Project Structure: The project structure will look like this.

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 }
});
  
var query = User.find()
  
var polyA = [[[ 11, 21 ], [ 11, 41 ], [ 31, 41 ], [ 31, 21 ]]]
query.where('loc').within()
            .geometry({ type: 'Polygon', coordinates: polyA })
  
console.log(query._conditions.loc)

Run index.js file using below command:

node index.js

Output: 

{
  '$geoWithin': { '$geometry': { 
    type: 'Polygon', coordinates: [Array] } }
}

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 }
});
  
var query = User.find()
  
var polyA = [[[ 15, 25 ], [ 15, 45 ], [ 35, 45 ], [ 35, 25 ]]]
query.where('loc').within()
            .geometry({ type: 'Polygon', coordinates: polyA })
  
console.log(query._conditions.loc)
  
app.listen(3000, function(error ) {
    if(error) console.log(error)
    console.log("Server listening on PORT 3000")
});

Run index.js file using below command: 

node index.js

Output: 

Server listening on PORT 3000
{
  '$geoWithin': { '$geometry': { 
     type: 'Polygon', coordinates: [Array] } }
}

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :