前言
在实际应用中,我们经常需要根据地理位置信息进行查询和存储。而多边形查询是其中的一个常见需求,例如查询某个区域内的商家或者用户。在 Node.js 中,Mongoose 是一个流行的 MongoDB ODM(Object Document Mapping)库,它提供了很多方便的查询和存储方法。本文将介绍如何使用 Mongoose 和 mongoose-geojson-polygon 插件进行多边形的查询和存储。
安装和配置
首先,我们需要安装 Mongoose 和 mongoose-geojson-polygon。可以使用 npm 进行安装:
npm install mongoose mongoose-geojson-polygon
安装完成后,在 Node.js 中引入 Mongoose 和 mongoose-geojson-polygon:
const mongoose = require('mongoose');
const geojson = require('mongoose-geojson-polygon');接下来,我们需要在 Mongoose Schema 中使用 geojson 类型,例如:
const UserSchema = new mongoose.Schema({
name: String,
location: {
type: geojson,
index: '2dsphere'
}
});在上面的示例中,location 字段使用了 geojson 类型,并且配置了 2dsphere 索引。这个索引可以提高查询效率,因为它支持地理位置的查询。
存储多边形
在存储多边形之前,我们需要定义一个多边形的 Schema,例如:
const PolygonSchema = new mongoose.Schema({
name: String,
coordinates: {
type: [[[Number]]],
required: true
}
});在上面的示例中,coordinates 字段使用了 [[[Number]]] 类型,表示一个三维数组,用来存储多边形的坐标。注意,这个字段是必需的。接下来,我们可以使用 Mongoose 的模型来保存多边形:
// www.javascriptcn.com code example
const Polygon = mongoose.model('Polygon', PolygonSchema);
const polygon = new Polygon({
name: 'Example',
coordinates: [
[
[0, 0],
[0, 10],
[10, 10],
[10, 0],
[0, 0]
]
]
});
polygon.save(function(err) {
if (err) {
console.error(err);
} else {
console.log('Polygon saved');
}
});在上面的示例中,我们创建了一个名为 Example 的多边形,并将它保存到 MongoDB 中。
查询多边形
查询多边形是本文的重点。我们可以使用 Mongoose 的 find 方法和 $geoIntersects 运算符来查询多边形。例如:
// www.javascriptcn.com code example
const User = mongoose.model('User', UserSchema);
User.find({
location: {
$geoIntersects: {
$geometry: {
type: 'Polygon',
coordinates: [
[
[5, 5],
[5, 15],
[15, 15],
[15, 5],
[5, 5]
]
]
}
}
}
}, function(err, users) {
if (err) {
console.error(err);
} else {
console.log(users);
}
});在上面的示例中,我们查询了所有在一个以 (10, 10) 为中心,半径为 10 的圆形区域内的用户。这个查询的关键在于 $geoIntersects 运算符,它表示查询和多边形相交的文档。
结语
本文介绍了如何使用 Mongoose 和 mongoose-geojson-polygon 插件进行多边形的查询和存储。多边形查询是一个常见的需求,它可以用来查询某个区域内的商家或者用户。希望本文对读者有所帮助。完整的示例代码可以在下面找到:
// www.javascriptcn.com code example
const mongoose = require('mongoose');
const geojson = require('mongoose-geojson-polygon');
mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true });
const UserSchema = new mongoose.Schema({
name: String,
location: {
type: geojson,
index: '2dsphere'
}
});
const PolygonSchema = new mongoose.Schema({
name: String,
coordinates: {
type: [[[Number]]],
required: true
}
});
const User = mongoose.model('User', UserSchema);
const Polygon = mongoose.model('Polygon', PolygonSchema);
const polygon = new Polygon({
name: 'Example',
coordinates: [
[
[0, 0],
[0, 10],
[10, 10],
[10, 0],
[0, 0]
]
]
});
polygon.save(function(err) {
if (err) {
console.error(err);
} else {
console.log('Polygon saved');
User.find({
location: {
$geoIntersects: {
$geometry: {
type: 'Polygon',
coordinates: [
[
[5, 5],
[5, 15],
[15, 15],
[15, 5],
[5, 5]
]
]
}
}
}
}, function(err, users) {
if (err) {
console.error(err);
} else {
console.log(users);
}
});
}
});来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/6785dafc5638eae96016179e