Reputation: 7590
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:
{'$set':{value:70}}
I am unsure of how can I save the type of field, please?
Upvotes: 0
Views: 2281
Reputation: 523
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.
Upvotes: 1
Reputation: 203519
It sounds like you have a property value
declared in your schema of type String
:
value : String
This will make Mongoose cast values to string, regardless of the strict
setting (which is not related to casting but whether or not to allow undeclared properties in your documents).
You should declare it as a Number
instead, because you're writing "there's a python script that reads certain properties from this collection, and it expects this form as int". In other words: you want documents in the database to have a numerical value
field.
This will still allow string valued value
fields serving as input to Mongoose operations, because Mongoose will cast them to numbers before writing to the database.
If you want to allow both strings and numbers to be written as-is to the database, you need to use mongoose.Schema.Types.Mixed
. This basically means that Mongoose will allow anything as input, and it will write the value as-is to the database (no casting). However, since you're saying that the Python tool expects numbers, I'd expect that you want to make sure that numbers are written to the database.
Upvotes: 0