【问题标题】:Check `type` of bson field to determine if it's a $numberDecimal (mongo/node)检查 bson 字段的 `type` 以确定它是否是 $numberDecimal (mongo/node)
【发布时间】:2022-01-13 17:42:21
【问题描述】:

我正在处理 mongo 聚合管道结果。我需要将 Decimal128 值转换为数字。例如

amount: { $numberDecimal: '200' } <-- dont want
amount: 200 // <-- desired format

棘手的部分是我想递归检查每个属性,只有当它是小数时,然后将其更改为数字。所以我的问题是,确定 bson 对象是否为 NumberDecimal 的最佳方法是什么?我能够通过第一次调用来实现这一点

JSON.parse(JSON.stringify(object))  

// Before parsing:
// Decimal128 {_bsontype: 'Decimal128', bytes: <Buffer 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3c 30> }
// After parsing:
// amount: { $numberDecimal: '200' }

然后检查每个对象是否具有$numberDecimal 属性,如果有,则在该值上调用Number()。总的来说,这似乎是实现这一目标的一种迂回方式。

有没有更好的方法不涉及解析对象并查找 $numberDecimal 键;我希望我能够检查 bson 对象的 typeof 或 instanceof,但它只是 object:(

这是我的函数(有效),但我觉得肯定有比检查 $numberDecimal 键更好的方法。

  const recursivelyMutateNumDec = (object) => {
    const jsonObj = JSON.parse(JSON.stringify(object));
    for (const k in (jsonObj)) {
      if (typeof jsonObj[k] === 'object' && jsonObj[k] !== null) {
        if (jsonObj[k]?.$numberDecimal) {
          // eslint-disable-next-line no-param-reassign
          jsonObj[k] = Number(object[k]);
        } else recursivelyMutateNumDec(jsonObj[k]);
      }
    }
    return jsonObj;
  };

欣赏任何见解/建议!

【问题讨论】:

  • instanceof检查类型而不是typeof
  • 我想我不知道将它与 instanceof 进行比较,例如(object[k] instanceof ?)?记录这些对象之一的构造函数显示:&lt;ref *1&gt; [Function: Decimal128] { fromString: [Function (anonymous)], Decimal128: [Circular *1] } 但我不确定我会从哪里得到Decimal128 以便在 instanceof 中使用它进行比较?

标签: node.js json mongodb mongoose bson


【解决方案1】:

Decimal128 是 BSON 类型。如果你导入它:

const { Decimal128 }  = require('bson');

您可以检查代码中的类型如下:

if (object[k] instanceof Decimal128) {

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多