NodeJS MongoDB Driver: Specify type of field at insert

Viewed 290

How can I specify or in other words enforce a particular type when inserting a document? For example,

{
    a: 1,
    b: 2
},
{
    a: 1.5,
    b: 1.5
}

and I would like to define to MongoDB to threat all fields as Double in this case. This is because there's no such thing as Integer in JavaScript an all Integers are Doubles by default although the decimal point vanishes when there is no decimal point. This behavior actually causes a problem when inserting documents to MongoDB from NodeJS because it is weakly typed.

I would like to emphasize that I'm not a big fan of Mongoose and please do not suggest me to use that! I wanna know how to explicitly specify types when inserting using the original MongoDB driver.

3 Answers

you can use

var { Double } = require("mongodb");

const item = { 
   a: Double(1),
   b: Double(2)
}

Even if Javascript uses doubles by default for all numbers, MongoDB's Javascript driver is a pain in the ass and has decided to use 32-bit int types by default for numbers that are integers and doubles for everything else. So you will end up with types in the DB that may seem random. The only way I have found to fix this is to define any number as mongodb.Double() explicitly, which is really inconvenient:

import * as mongodb from 'mongodb';

const obj = { a: new mongodb.Double(0) };
// Now you can save it to the DB and obj.a will be a double instead of a 32-bit integer

// If you need to convert it back to a number to operate with it:
console.log(obj.a.valueOf() + 1);

This will fill up your codebase with new mongodb.Double() and .valueOf() calls, and MongoDB, Inc. doesn't seem to care about it!

Use js-bson and specify the types explicitly.

To enforce the types on the server side, use schema validation.

Related