'Make Node MongoDB driver return bson classes for queries
I'm using Node MongoDB driver (mongodb) to do some simple db.collection.find(). I then stringify using bsons EJSON, send it and might re-use it for MongoDB at the other end.
To preserve data type I'd like for the Document instances to always use the bson classes like Int32 and Long, however the result appears to be number a lot of the time and then Long when required.
Is there any way to enforce using the bson classes?
Solution 1:[1]
The term for the conversion being done from bson classes to closest JavScript equivalent is apparently promoteValues (API reference). Essentially:
when deserializing will promote BSON values to their Node.js closest equivalent types.
It can be used in most operations, e.g.:
import { MongoClient } from "mongodb"
const client = new MongoClient("mongodb://localhost:27017")
const collection = client.db("mydatabase").collection("mycollection")
const cursor = collection.find({}, { promoteValues: false }) // keep bson classes
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Halvor Holsten Strand |
