Skip to content
Related Articles

Related Articles

Improve Article
How does Query.prototype.centerSphere() work in Mongoose ?
  • Last Updated : 12 Mar, 2021

The Query.prototype.centerSphere() function defines a circle for a geospatial query that uses spherical geometry. It returns the all the documents which are within the bounds of the circle.

Syntax:

Query.prototype.centerSphere()

Parameters: This function has one value parameter, and an optional path parameter.
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

Now, 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 }
});
  
var query = User.find();
var area = { center: [20, 20], radius: 5, unique: true }
query.where('loc').within().centerSphere(area)
  
console.log(query._conditions.loc.$geoWithin)

 

  1. The project structure will look like this:

node index.js

Output

{ '$centerSphere': [ [ 20, 20 ], 5 ], '$uniqueDocs': true }

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 area = { center: [10, 10], radius: 50, unique: true }
query.where('loc').within().centerSphere(area)
  
console.log(query._conditions.loc.$geoWithin)
  
app.listen(3000, function(error ) {
    if(error) console.log(error)
    console.log("Server listening on PORT 3000")
});

 

  1. The project structure will look like this:

node index.js

Output

Server listening on PORT 3000
{ '$centerSphere': [ [ 10, 10 ], 50 ], '$uniqueDocs': true }

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :