我正在开发一个应用程序,它(除其他外)允许 CSV 上传,将其转换为 JSON,然后将 JSON 导入 mongo。
我有一个看起来像这样的架构:
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);
我有一个导入脚本,它循环遍历 JSON 对象并根据模式持续存在:
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);
...
}
然而,正如我所说,任何对象的数量都包含逗号,例如1,120.55
不会持久化。
我已经尝试过 mongoose-currency 来解决这个问题,但最后我得到了一个值,例如 112055。文档说在向用户显示时使用 .toFixed(2)
但我正在运行我的 route 的一个 .find()
查询,然后传递给 Handlebars 进行渲染。
我尝试过各种 Handlebars 功能
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,");
});
(以及 format.js 和 handlebars.numeral)尝试更正格式,但我不太正确。
所以我的问题是 - 将带逗号的值导入 mongo 然后将其显示给用户的最佳方式是什么?
最佳答案
我做了一些实验,发现:
parseFloat("1,120.55"); // 1
parseInt("1,120.55"); // 1
所以我看到的最简单的一点是用替换函数清理 ,
newStatement.amount = Number(statements[i].amount.replace(/,/g, ''));
这应该可以解决问题。 之后您需要创建一个格式化助手来显示逗号。
关于node.js - MongoDB/Mongoose - 用逗号导入数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43725847/