Query.prototype.box() 如何在Mongoose中工作?
Query.prototype.box()用于指定 $box 条件。使用此函数时, $geoWithin根据网格坐标返回文档。
句法:
Query.prototype.box()
参数:该函数有一个数组对象参数,它有左上坐标和右上坐标。
返回值:此函数返回查询对象。
安装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 }
});
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)
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")
})
项目结构将如下所示:
使用以下命令运行index.js文件:
node index.js
输出:
Geo Location within: { '$box': [ [ 23, -71 ], [ 12, 11 ] ] }
示例 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")
})
项目结构将如下所示:
使用以下命令运行index.js文件:
node index.js
输出:
Server listening on PORT 3000
Geo Location is: { '$box': [ [ 21, -33 ], [ -6, 32 ] ] }
参考: https://mongoosejs.com/docs/api/query.html#query_Query-box