Node.js 如何使用mongoose添加GeoJson数据?
我正在发送对象以创建用户模型Node.js 如何使用mongoose添加GeoJson数据?,node.js,mongoose,geojson,Node.js,Mongoose,Geojson,我正在发送对象以创建用户模型 "{ type: 'Point', coordinates: [ 25.2239771, 51.4993224 ] }" 这是我创建的猫鼬模式 const mongoose = require('mongoose'); const Schema = mongoose.Schema; const UserProfileSchema = new Schema( { userId: { type: String,
"{
type: 'Point',
coordinates: [ 25.2239771, 51.4993224 ]
}"
这是我创建的猫鼬模式
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserProfileSchema = new Schema(
{
userId: {
type: String,
// required: true,
unique: true,
},
userFirstName: {
type: String,
// required: true,
},
userLastName: {
type: String,
// required: true,
},
userGender: {
type: String,
// required: true,
},
userCoordinates: {
type: {
type: String,
default: 'Point',
},
coordinates: {
type: [Number],
index: '2dsphere',
},
},
},
{ collection: 'userprofilemodels' }
);
module.exports = UserProfile = mongoose.model(
'userprofilemodels',
UserProfileSchema
);
这是我用来添加geoJson类型文件的代码。然而,我得到了一个错误。
我还尝试在定义模式后添加索引
await new userProfileModel({
userId,
userFirstName,
userLastName,
userCoordinates,
})
.save()
.then(() => {
console.log('it worked!');
res.send('worked!');
})
.catch((error) => {
console.log('did not worl')
// console.log(error);
});
如果我排除userCoordinates,那么它就起作用了。因此,def我的geoJson对象是错误的。但是,我不知道我在哪里犯了错误。取自mongoose,似乎GeoJSON类型不能只是字符串
以下是location
作为GeoJSON类型的示例:
const citySchema=newmongoose.Schema({
名称:String,
地点:{
类型:{
type:String,//不执行`{location:{type:String}}`
枚举:['Point'],//'location.type'必须是'Point'
必填项:true
},
坐标:{
类型:[编号],
必填项:true
}
}
});
Mongoose支持GeoJSON对象索引,因此首先将“2dsphere”索引添加到用户坐标,而不是对象内的坐标,以使其正常工作
userCoordinates: {
type: {
type: String,
default: 'Point',
},
coordinates: {
type: [Number],
default: undefined,
required: true
},
index: '2dsphere'
},
确保您的用户坐标如下所示:
const userCoordinates = {
type: "Point",
coordinates: [coordinatesA, coordinatesB],
};
它看起来很管用。但是,只有在刷新节点时,才会以某种方式应用索引。有什么方法可以从一开始就应用它吗?这种索引是在集合创建时应用的,这是一种预期的行为,因为我们不应该在生产时调整索引。从现在起它应该会起作用