我试图使用Mongoose将多边形存储到我的MongoDB数据库中。我已经尝试过所有替代方案,但不幸的是我无法弄清楚。我发现了一种将坐标存储为字符串的方法,但不能将其存储为geoJSON数组(Polygons)。
organization
对象的territory
属性应该是polygon
,应该存储在一个数组中。
我使用POSTMAN
出于测试目的,而下方则是坐标的我POST请求的截图:
如何使用NodeJS和Mongoose将多边形坐标(GeoJSON)作为数组存储到MongoDB数据库中
当我提交我的职务要求,我得到这个错误回:
这里是如何将对象存储在数据库中,作为一个字符串而不是一个点的数组
我已经尝试了以下代码的多个版本,我要么获得上述响应o另一个说明cast to array failed for value...
。
请告诉我我做错了什么或如何得到这个工作。
以下是我的代码。
Organization.js
var mongoose = require('mongoose');
var organizationSchema = mongoose.Schema({
name:String,
address:String,
point:{type:[Number],index:'2d'},
territory:{
type:{
type:String,
required:true,
enum:['Point','LineString','Polygon'],
default:'Point'
},
coordinates:[mongoose.Schema.Types.Mixed]
}
});
organizationSchema.index({coordinates:'2dsphere'});
API.js
var Organization = require('./models/organization');
var express = require('express');
var mongoose = require('mongoose');
var apiRoutes = express.Router();
apiRoutes.route('/organizations')
.post(function(req,res,next){
var organization = new Organization();
var pointData = {
latitude:req.body.latitude,
longitude:req.body.longitude
};
var loc = req.body.coordinates;
organization.name = req.body.name;
organization.address = req.body.address;
organization.latitude = req.body.latitude;
organization.longitude = req.body.longitude;
organization.point = [pointData.longitude,pointData.latitude];
organization.territory = {
coordinates: loc,
type: req.body.type
};
//save the new organization and check for errors
organization.save(function (err, organization) {
if (err)
return res.send(err)
res.json({
message: 'The Organization was successfully created!',
Organization: organization
});
});
});
你还需要答案吗? –
我还是这么做的。你的回答是可以接受的 – AllJs