Query.prototype.centerSphere() 如何在Mongoose中工作?
Query.prototype.centerSphere()函数为使用球面几何的地理空间查询定义了一个圆。它返回圆圈范围内的所有文档。
句法:
Query.prototype.centerSphere()
参数:此函数有一个值参数和一个可选的路径参数。
返回值:此函数返回查询对象。
安装mongoose:
npm install mongoose
安装mongoose模块后,您可以使用命令在命令提示符下检查您的mongoose版本。
npm mongoose --version
现在,创建一个文件夹并添加一个文件,例如 index.js,如下所示。
示例 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().centerSphere(area)
console.log(query._conditions.loc.$geoWithin)
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: [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")
});
- 项目结构将如下所示:
node index.js
输出:
{ '$centerSphere': [ [ 20, 20 ], 5 ], '$uniqueDocs': true }
示例 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: [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")
});
- 项目结构将如下所示:
node index.js
输出:
Server listening on PORT 3000
{ '$centerSphere': [ [ 10, 10 ], 50 ], '$uniqueDocs': true }
参考: https://mongoosejs.com/docs/api/query.html#query_Query-centerSphere