【问题标题】:Mongoose Latitude & Longitude validation is not working while saving in mongo?在 mongo 中保存时,Mongoose 纬度和经度验证不起作用?
【发布时间】:2016-03-15 19:14:50
【问题描述】:

以下是我的位置集合架构:

var LocationSchema = new Schema({
    street : {type: String, required: true},
    area : {type: String, required: true},
    city : {type: String, required: true},
    state : {type: String, required: true},
    zip : {type: String, required: true},
    country : {type: String, default: 'IN'},
    pointers:{type: [], index: '2dsphere'}
});

使用 mongoose 指针在 mongo 中保存数据时,存储为字符串而不是数字。得到以下回复:

"street": "rani sati marg",
"area": "malad east",
"city": "mumbai",
"state": "maharashtra",
"zip": "400097",
"pointers": [
    "72.857452,19.857452"
],
"country": "IN"

我想要数字中的指针值,例如:[72.857452,19.857452]

【问题讨论】:

  • 您实际上并没有要求它。 "pointers": { "type": [Number], "index": "2dphere" } 实际上声明数组中的内容 必须 是数字,并且在像您所做的那样发送“字符串”数组时将“自动转换”。
  • 然后在验证时将 Cast to Array 转换为值错误。

标签: node.js mongodb mongoose


【解决方案1】:

错过了字符串在源数据中包含逗号。

为此,您仍然需要架构中的数字“类型”:

"pointers": { "type": [Number], "index": "2dphere" }

但是您想要一个“setter”函数来为您进行转换:

LocationSchema.path("pointers").set(function(value) {
    if ( typeof(value[0]) == "string" && value.length == 1 ) {
        return value[0].split(",");
    } else {
        return value;
    }
});    

就是这样。数组中的 Number 类型将为您计算从“字符串”到数字的转换,因此不需要 parseFloat 或类似的东西,因为它已经被处理了。

“setter”中你真正需要的只是解决这个问题:

“如果我得到的数组包含一个字符串并且只有一个元素,那么我认为它是逗号分隔的,并将该字符串拆分为一个数组。

您可能想要做一些比这更严格的逻辑,但这是对传递给“setter”的数据实现转换的基本方法。

给我:

pointers: [ 72.857452, 19.857452 ]

就像它应该的那样。

【讨论】:

  • 使用上述解决方案得到Cast to Array failed for value \"72.857452,19.857452\"这个错误
  • @AsheshKhatri 不,如果您实际使用了.set(),如答案所示,您没有这样做。因此,如果您实际上是在提交像"pointers": [ "72.857452,19.857452"] 这样的数据,并且像您的问题所问的那样在数组中使用单个字符串,那么所提供的“setter”的函数会将该字符串拆分为一个由两个元素组成的数组并相应地设置值。实际上,您只是提交"pointers": "72.857452,19.857452",而不是查看value0 索引,而是直接在value 上测试并发出split(),即return value.split(",")
猜你喜欢
  • 1970-01-01
  • 2011-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-14
  • 2011-08-04
  • 1970-01-01
  • 2020-07-18
相关资源
最近更新 更多