I\'m querying Mongo in Nodejs with Mongoose and attempting to extract the numeric value of multiple fields stored as a Decimal128. However, the value is oddly wrapped in que
This will work with any field!
It supports subdocument and arrays of subdocuments too
const MySchema = new Schema({/*... schema fields ...*/});
const decimal2JSON = (v, i, prev) => {
if (v !== null && typeof v === 'object') {
if (v.constructor.name === 'Decimal128')
prev[i] = v.toString();
else
Object.entries(v).forEach(([key, value]) => decimal2JSON(value, key, prev ? prev[i] : v));
}
};
MySchema.set('toJSON', {
transform: (doc, ret) => {
decimal2JSON(ret);
return ret;
}
});
mongoose.model('MyModel', MySchema);
Usage:
MyModel.findOne().then(data => console.log(data.toJSON());