猫鼬:因值“ [[2.3635503,48.8674024] ....]]”而强制转换为数组

时间:2019-02-12 11:22:40

标签: mongoose

当我用猫鼬将位置点保存在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,....

testSchema1testSchema2有什么区别?

可以在testSchema1中添加验证吗?

例如:

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

1 个答案:

答案 0 :(得分:0)

https://mongoosejs.com/docs/schematypes.html#arrays中,您可能会争辩说第一个模式是文档数组,第二个模式是原始数组。

来自此线程 How to define object in array in Mongoose schema correctly with 2d geo index,我想说要使第一个模式像第二个模式一样工作,应使用releasePoints编写它,如下所示:

 releasePoints: [{
    type: Array , default: []
  }]

然后添加一个验证器以检查“数字类型插入”。 或类似的东西:

releasePoints: [{
   data: [Number]
}]

但是您应该使用数据属性[x] .data [y]

访问该值

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

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