Mongoose:value“的强制转换到数组失败;[2.3635503,48.8674024]……”;

Mongoose:value“的强制转换到数组失败;[2.3635503,48.8674024]……”;,mongoose,Mongoose,当我用猫鼬在mongo中保存位置点时,我遇到了一个奇怪的问题 const testSchema1 = new mongoose.Schema({ releasePoints: [{ type: [Number] }] }, { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' } }); const testSchema2 = new mongoose.Schema({ re

当我用猫鼬在mongo中保存位置点时,我遇到了一个奇怪的问题

const testSchema1 = new mongoose.Schema({
  releasePoints: [{
    type: [Number]
  }]
}, {
  timestamps: {
    createdAt: 'created_at',
    updatedAt: 'updated_at'
  }
});

const testSchema2 = new mongoose.Schema({
  releasePoints: [[Number]]
}, {
  timestamps: {
    createdAt: 'created_at',
    updatedAt: 'updated_at'
  }
});
当我使用
testSchema2
成功保存数据时,但我使用
testSchema1
throw err

validation failed: releasePoints: Cast to Array failed for value "[ [ 2.3635503,....
testSchema1
testSchema2
有什么区别

是否可以在
testSchema1
中添加验证

例如:

const testSchema1 = new mongoose.Schema({
  releasePoints: [{
    type: [Number],
    validate: (val) => val.length === 2
  }]
}, {
  timestamps: {
    createdAt: 'created_at',
    updatedAt: 'updated_at'
  }
});

从中可以看出,第一个模式是文档数组,第二个模式是基元数组

从这根线 ,我想说的是,要使第一个模式的行为与第二个模式的行为类似,您应该使用如下的releasePoints编写它:

 releasePoints: [{
    type: Array , default: []
  }]
然后添加一个验证器来检查“数字类型插入”。 或者类似于:

releasePoints: [{
   data: [Number]
}]
但是您应该使用数据属性[x]访问该值

如果需要保存纬度/经度值,只需执行以下操作:

releasePoints: [{
   lat: Number,
   long: Number
}]
从中可以看出,第一个模式是文档数组,第二个模式是基元数组

从这根线 ,我想说的是,要使第一个模式的行为与第二个模式的行为类似,您应该使用如下的releasePoints编写它:

 releasePoints: [{
    type: Array , default: []
  }]
然后添加一个验证器来检查“数字类型插入”。 或者类似于:

releasePoints: [{
   data: [Number]
}]
但是您应该使用数据属性[x]访问该值

如果需要保存纬度/经度值,只需执行以下操作:

releasePoints: [{
   lat: Number,
   long: Number
}]

对不起,我不太擅长评论。我更新了我的问题描述。对不起,我不太擅长评论。我更新了我的问题描述,因为我不明白你到底在搜索什么。是否要向架构添加验证以验证数组长度?您需要解决强制转换错误吗?或者您需要创建一个模式来拥有一个经度和纬度数组吗?您还可以添加您在示例中所做的插入查询吗?我不知道您到底在搜索什么。是否要向架构添加验证以验证数组长度?您需要解决强制转换错误吗?或者您需要创建一个模式来拥有经度和纬度的数组吗?您还可以添加您在示例中所做的插入查询吗?