【问题标题】:Getting a null in my console while retrieving the data from mongodb database从 mongodb 数据库中检索数据时在我的控制台中获取 null
【发布时间】:2020-09-10 17:59:39
【问题描述】:

我正在尝试从数据库中访问数据,数据存储在距离字段中,但是在检索它时,我在控制台中得到了空值。

谁能帮帮我?

connection done
null

我正在使用以下代码

mongoose.connect(db)
.then(()=>{
    console.log('connection done')
})
.catch(err =>{
    console.log(err)
})
const query = new schema({
    distance:{
        type:String
    }
})

const per = mongoose.model('iot',query)
per.findOne({distance:2887.2021794319153})
.then(person=>{
    console.log(person)

})
.catch(err=>console.log(err))

输出应该是整个文档及其 id 和距离,但我得到一个 NULL 作为输出

【问题讨论】:

  • 数据已经通过pymongo使用rasberrypi上传到数据库

标签: node.js mongodb mongoose


【解决方案1】:

计算机并不擅长准确地表示十进制数。以数字格式存储的任何实数只是所提供值的近似表示。您可以在此处阅读更多信息:https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html。这种推理也适用于 MongoDB。

在这种情况下,DB 中distance 的值将是2887.2021794319153 的近似表示。在查询中传递的值(来自 JavaScript)也将是相同数字的近似值。两个近似值不必总是“严格”相等。这就是为什么在处理浮点算术时应该依赖“范围”而不是“相等”。尝试以下查询:

const per = mongoose.model('iot',query);
per.findOne({
    distance: { 
        $gt: 2887.2021794319152,
        $lt: 2887.2021794319154
    }
})
.then(person=>{
    console.log(person)

})
.catch(err=>console.log(err))

在此示例代码中,我们不是在寻找 distance 的精确小数值,而是在 2887.2021794319152(原始值减去 1 的最低有效位)和 2887.2021794319154(原始值加上 1 的最低有效位)之间的值数字)。您可能需要根据系统/语言稍微扩大范围。

【讨论】:

  • 但我无法更改距离值,它是使用 pymongo 的超声波传感器的实时传感器值
  • 即使它的实时传感器值,您应该能够将您的查询更改为一个范围。例如,假设传感器值在一个名为 sensorVal 的变量中,那么您的查询可能是:{ distance: { "$gt": sensorVal - 0.000001, "$lt": sensorVal + 0.000001 } }
猜你喜欢
  • 2021-07-20
  • 2021-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-27
  • 2019-01-19
  • 2023-03-15
  • 2021-05-21
相关资源
最近更新 更多