【问题标题】:Mongoose: Cast to Array failed for value "[ [ 2.3635503, 48.8674024 ]....]]"Mongoose:值“[ [ 2.3635503, 48.8674024 ]....]] 时转换为数组失败
【发布时间】:2019-07-06 00:53:40
【问题描述】:

我在mongoose中保存位置点时遇到了一个奇怪的问题。

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保存数据成功,但我使用testSchema1throw 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'
  }
});

【问题讨论】:

  • 我不明白你在寻找什么。您想向您的架构添加验证以验证数组长度吗?您需要解决演员阵容错误吗?或者您是否需要创建一个架构来包含经度和纬度数组?
  • 您还可以添加您在示例中所做的插入查询吗?

标签: mongoose


【解决方案1】:

来自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
}]

【讨论】:

  • 对不起,我对 cme​​ts 不是很熟练。我更新了我的问题描述
猜你喜欢
  • 2018-07-12
  • 2013-03-24
  • 2018-10-21
  • 2015-10-29
  • 2021-09-05
  • 2021-03-09
  • 1970-01-01
  • 2018-01-06
  • 1970-01-01
相关资源
最近更新 更多