gpt4 book ai didi

node.js - Node ,js - Mongoose - 无法保存地理多边形 - CastError : Cast to number failed

转载 作者:可可西里 更新时间:2023-11-01 10:32:13 26 4
gpt4 key购买 nike

我正在尝试将地理点和地理多边形保存到 Mongo。我的点测试通过,但多边形失败:

CastError: Cast to number failed for value "0,0,3,0,3,3,0,3,0,0" at path "coordinates"

我的架构如下:

var GeoSchema = new Schema({
name: String
, coordinates: [Number]
});
GeoSchema.index({ coordinates: '2dsphere' });

我成功保存的测试点对象:

geoPoint = new Geo({
coordinates: [2,2],
type: 'Point'
});

无法保存的我的测试多边形对象:

geoPolygon = new Geo({ 
type: 'Polygon',
coordinates: [[ [0,0], [3,0], [3,3], [0,3], [0,0] ]]
});

我曾尝试将“坐标”的类型定义更改为对象和数组,但都无法保存。

谁能给个建议?


* 更新 *

我现在可以让测试通过:

架构:

var GeoSchema = new Schema({
coordinates : { type: [], index: '2dsphere' },
type: String
});

点对象:

geoPoint = new Geo({
geo: {
type: 'Point',
coordinates: [2,2]
}
});

多边形:

    geoPolygon = new Geo({ 
geo: {
type: 'Polygon',
coordinates: [
[ [100.0, 0.0], [101.0, 0.0],
[101.0, 1.0], [100.0, 1.0],
[100.0, 0.0] ]
]
}
});

然而,当我直接查询数据库时,我只看到:

db.geos.find()
{ "_id" : ObjectId("52b73de00b4dfee427000005"), "__v" : 0 }
{ "_id" : ObjectId("52b73de00b4dfee427000006"), "__v" : 0 }

谁能告诉我为什么看不到保存的记录?

最佳答案

编辑:看来我们只能在Point上设置2dsphere,不能在Polygon上设置

所以我删除了索引,它起作用了。

文件:app.js

var mongoose = require('mongoose');

mongoose.connect('localhost', 'geo-database');

var GeoSchema = mongoose.Schema({
name: String
, coordinates: []
});

//GeoSchema.index({ coordinates: '2dsphere' });

var Geo = mongoose.model('geos', GeoSchema);

Geo.on('index', function () {
function cb() {
console.log(arguments);
}

geoPoint = new Geo({
coordinates: [2,2],
type: 'Point'
}).save(cb);

geoPolygon = new Geo({
type: 'Polygon',
coordinates: [[ [0,0], [3,0], [3,3], [0,3], [0,0] ]]
}).save(cb);
})

终端:

$mongo --version
MongoDB shell version: 2.5.5-pre-

npm install mongoose
node app

输出:

{ '0': null,
'1': { __v: 0, _id: 52b6e82493d21060b3000001, coordinates: [ 2, 2 ] },
'2': 1 }
{ '0': null,
'1':
{ __v: 0,
_id: 52b6e82493d21060b3000002,
coordinates: [ [ [Object], [Object], [Object], [Object], [Object] ] ] },
'2': 1 }

关于node.js - Node ,js - Mongoose - 无法保存地理多边形 - CastError : Cast to number failed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20728887/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com