swateek swateek - 1 year ago 160
Node.js Question

MongoDB insert from NODEJS converts data type of value from int to string

I am trying to update an integer from NodeJS to a MongoDB collection, and however ways I have tried it always converts the integer into a string in the collection.

Please note, I cannot have a strict mongoose schema.

Here's my update function:

_getModel("envSettings").update(query, toUpdate , {upsert: insertIfNotFound}, function(err, docs){
_prepResponse(err, docs, callback);

The inputs to this piece of code is like this:

insertIfNotFound: false
query: {'_id':'somekey'}

And here are the variety of toUpdate I have tried:

toUpdate: {$set:{value: 70}}
toUpdate: {$set:{value: parseInt(70)}}
toUpdate: {$set:{value: mongodb.Long(70).toInt()}}

When printing any of the above toUpdate to console, the output is always the same:


I am unsure of how can I save the type of field, please?

Answer Source

To check all three variation use typeof because display in print function will be same always. It is my personal preference to Insert all as string and while displaying check for numeric value, if you find value to be numeric then process it accordingly.

Also storing all data as string will help you in making your queries as well.

Edit - I used the second approach for my problem.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download