Type alias CollNumCoercion

CollNumCoercion: "number" | "strict_number" | "bigint" | "bignumber" | "string" | "number_or_string" | ((val, path) => unknown)
Overview

💡Tip: read the documentation for CollectionSerDesConfig.enableBigNumbers before reading this.

The CollNumCoercion type is used to define how numeric values should be coerced when deserializing data in collections.

Each type of coercion has its own characteristics, and the choice of coercion should be well-thought-out, as misuse may lead to unexpected behavior and even damaged data.


Under the hood

✏️Note: in this context, "large" means that a number is not perfectly representable as a JS number.

Under the hood, the specialized JSON parser converts every number to either a number or a BigNumber, depending on its size. From there, the coercion function is applied to the value to convert it to the desired type.

This means that coercion is applied after parsing, and certain coercions may fail if the value is not compatible with the coercion type.

  • For example, coercing a BigNumber to a number may fail if the value is too large to fit in a number.
  • In this case, the coercion function will throw a NumCoercionError error.

Predefined coercions

Type: number

  • Description: Coerces the value to a number, possibly losing precision if the value is too large.
  • Throws?: No.

Type: strict_number

  • Description: Coerces the value to a number, only if the value not too large to be a number.
  • Throws?: Yes, if the value is too large to fit in a number.

Type: bigint

  • Description: Coerces the value to a bigint, only if the value is an integer.
  • Throws?: Yes, if the value is not an integer.

Type: bignumber

  • Description: Coerces the value to a BigNumber.
  • Throws?: No.

Type: string

  • Description: Coerces the value to a string.
  • Throws?: No.

Type: number_or_string

  • Description: Coerces the value to a number if it is not too large, otherwise coerces it to a string.
  • Throws?: No.

Custom coercions

You can also use a custom coercion function as the coercion type, which takes the value and the path as arguments and returns the coerced value.

Type declaration

Example

const coll = db.collection('coll', {
serdes: {
enableBigNumbers: {
'*': number,
'items.*.price': (val, path) => {
// nonsensical but demonstrative example
const itemIndex = path[1];
return BigNumber(value).times(itemIndex);
},
}
},
});

const { insertedId } = await coll.insertOne({
itemCount: 3,
items: [{ price: 10 }, { price: 20 }, { price: 30 }],
});

const item = await coll.findOne({ _id: insertedId });

console.log(item.itemCount); // 3
console.log(item.items[0].price); // BigNumber(0)
console.log(item.items[1].price); // BigNumber(20)
console.log(item.items[2].price); // BigNumber(60)

See

  • CollectionSerDesConfig.enableBigNumbers
  • CollNumCoercionFn
  • CollNumCoercionCfg
  • NumCoercionError