Home > Mobile >  Check `type` of bson field to determine if it's a $numberDecimal (mongo/node)
Check `type` of bson field to determine if it's a $numberDecimal (mongo/node)

Time:01-14

I'm working with a mongo aggregate pipeline result. I need to convert Decimal128 values to numbers. E.g.

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

The tricky part is I want to recursively check every property and only if it is a decimal, then change it to a number. So my question is, what is the best way to determine if the bson object is a NumberDecimal? I was able to achieve this by first calling

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' }

then checking if each object has a $numberDecimal property, and if it does then calling Number() on the value. Overall this just seems like a round-a-bout way to achieve this.

Is there a better way that doesn't involve parsing the object and looking for the $numberDecimal key; I expected I would be able to do something like check the typeof or instanceof the bson object, but it is just object:(

Here is my function (which works) but I feel there must be a better way than checking for the $numberDecimal key.

  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;
  };

Appreciate any insight/suggestions!

CodePudding user response:

Decimal128 is a BSON type. If you import it:

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

You can check the type in your code as following:

if (object[k] instanceof Decimal128) {
  •  Tags:  
  • Related