Open In App

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

Last Updated : 26 Mar, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

The Query.prototype.circle() function is used to specify a $center or $centerSphere condition. It specifies a circle for a $geoWithin query.
Syntax: 
 

Query.prototype.circle()


Parameters: This function has one area parameter and one 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

Database: The sample database used here is shown below.

Folder Structure:

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
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 }
});

var query = User.find();
var area = { center: [20, 20], radius: 5, unique: true }
query.where('loc').within().circle(area)

console.log(query._conditions.loc.$geoWithin)
Run index.js file using below command:
node index.js

Output:

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


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 }
});

var query = User.find();
var area = { center: [2, 2], radius: 15, unique: true }
query.where('loc').within().circle(area)

console.log(query._conditions.loc.$geoWithin)

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
{ '$center': [ [ 2, 2 ], 15 ], '$uniqueDocs': true }


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


Similar Reads