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)
Overview
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
Under the hood, the specialized JSON parser converts every number to either a
number
or aBigNumber
, 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.
BigNumber
to anumber
may fail if the value is too large to fit in anumber
.Predefined coercions
Type:
number
number
, possibly losing precision if the value is too large.Type:
strict_number
number
, only if the value not too large to be anumber
.number
.Type:
bigint
bigint
, only if the value is an integer.Type:
bignumber
BigNumber
.Type:
string
string
.Type:
number_or_string
number
if it is not too large, otherwise coerces it to astring
.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.