【问题标题】:ReferenceError: NumberDecimal is not defined in mongoDBReferenceError: NumberDecimal 未在 mongoDB 中定义
【发布时间】:2018-02-06 14:46:52
【问题描述】:

我尝试使用

db.orders.insert({"Price":NumberDecimal("12.34")})

它会抛出这个错误

"ReferenceError: NumberDecimal is not defined" 在 Node.js 中

但它在robo3T中运行良好

db.getCollection('orders').insert({"Price":NumberDecimal("12.34")})

MongoDB shell 版本:v3.4.7

MongoDB服务器版本:3.4.7

【问题讨论】:

  • 您能否edit 向我们展示您使用代码的上下文?尝试在没有 NumberDecimal() 包装器的情况下插入,即db.orders.insert({"Price": 12.34}, (err, result) => console.log(result));
  • 请再次验证shell版本,这应该从shell版本3.4开始工作
  • 这很好用 - db.orders.insert({"Price": 12.34}, (err, result) => console.log(result));
  • 但我的问题是为什么 NumberDecimal() 会抛出错误
  • 我仔细检查了 -MongoDB shell 版本:v3.4.7 MongoDB 服务器版本:3.4.7

标签: javascript node.js mongodb mean-stack


【解决方案1】:

NumberDecimal("12.34") 替换为mongodb.Decimal128.fromString('12.34')

【讨论】:

  • 这没有提供问题的答案。要批评或要求作者澄清,请在他们的帖子下方留下评论。 - From Review
  • 为什么不提供问题的答案? Decimal128 应该是等同于 NumberDecimal 的 nodejs mongodb 本机
【解决方案2】:

您无需在 NodeJS 中编写 NumberDecimal 在你写的时候

db.orders.insert({"Price":NumberDecimal("12.34")})

你可以把上面的查询写成

var price= parseFloat("12.34");
db.orders.insert({"Price" : price})

如果您使用的是 mongoose 模式,您可以定义结构的数据类型,mongo 将在插入时自动采用您在 mongoose 模式中定义的相关数据类型

【讨论】:

  • 当我尝试parseFloat 时,它插入为Double。 MongoDB shell 版本 v4.0.3。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-10
  • 1970-01-01
  • 2012-08-24
  • 1970-01-01
  • 2013-10-23
  • 2019-02-11
相关资源
最近更新 更多