MongoDB / Mongoose - Importing numbers with commas
I am working on an application that (among other things) allows you to upload a CSV, convert it to JSON, and then import the JSON into mongo.
I have a schematic that looks like this:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var statementSchema = new Schema({
date : {type:Date, required:true},
name: {type:String, required:true},
method: {type:String},
amount: {type:Number, required:true},
category: {type:String, default:'Not Set'},
importDate: {type : Date, default:Date.now, required:true}
});
statementSchema.index({"date":1, "name":1, "amount":1}, {unique: true});
module.exports = mongoose.model('Statement', statementSchema);
I have a script import that goes through a JSON object and is saved according to the schema:
for( var i = 0; i < statements.length; i++ ) {
.....
var newStatement = new Statement();
//the amount value is a string currently
newStatement.amount = Number(statements[i].amount);
...
}
However, as I say, any objects that have a sum that includes a comma, for example. 1,120.55
are not saved.
I tried mongoose-currency, which resolves the problem, but then I get a value like 112055. The docs say to use .toFixed(2)
when shown to users, but I run a request .find()
on my route, which is then passed to Handlebars for rendering.
I have tried various rudder functions
Handlebars.registerHelper('amountFixed', function(amount) {
return amount.toFixed(2);
});
Handlebars.registerHelper('amountCurrency', function(amount) {
return amount.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
});
(as well as format.js and handlebars.numeral) to try and fix the formatting, but I can't seem to get it right.
So my question is, what's the best way to import a semicolon value into mongo and then show it to the user?
source to share
I experimented and saw that:
parseFloat("1,120.55"); // 1
parseInt("1,120.55"); // 1
So the simplest point I can see is to clean up ,
with replace function
newStatement.amount = Number(statements[i].amount.replace(/,/g, ''));
And that should do the trick. And after you need to create a shaping helper to display the comma.
source to share