Reputation: 1
I am trying to create a Schema with a 'price' field using Mongoose currency and follow the documentation on it. However the output does not show two decimals (499 instead of 4.99). If I use console.log to print the price, it shows the desired results, with two decimals. I wonder whether I misunderstood the Mongoose documentation on Currency or does the cause lie somewhere else.
This is my schema.
var mongoose = require('mongoose');
var assert = require('assert');
var Dishes = require('./models/stackmodel');
// Connection URL
var url = 'mongodb://localhost:27017/conFusion';mongoose.connect(url);
var db = mongoose.connection;
var product = new Dishes({ price: '4.99' });
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
// we're connected!
console.log("Connected correctly to server");
// create a new dish
Dishes.create({
name: 'Uthapizza',
price: (product.price/100).toFixed(2),
}, function (err, dish) {
if (err) throw err;
console.log('Dish created!');
console.log(dish);
console.log(typeof (product.price/100).toFixed(2));
console.log((product.price/100).toFixed(2));
db.collection('dishes').drop(function () {
db.close();
});
});
});
This is my model.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
require('mongoose-currency').loadType(mongoose);
var Currency = mongoose.Types.Currency;
// create a schema
var dishSchema = new Schema({
name: {
type: String,
required: true,
unique: true
},
price: {
type: Currency,
require: true,
min: -20000,
max: 50000,
default: ''
}
});
var Dishes = mongoose.model('Dish', dishSchema);
// make this available to our Node applications
module.exports = Dishes;
And this is the print-out.
C:\ass2>node stack
Connected correctly to server
Dish created!
{ __v: 0,
name: 'Uthapizza',
_id: 58cd3dbd4319c51264489d8d,
price: 499 }
string
4.99
C:\ass2>
I have searched on the web, including on this site, but found no solution so far.
I use:
npm ERR! extraneous: [email protected] C:\node_modules\currency
npm ERR! extraneous: [email protected] C:\node_modules\mocha
npm ERR! extraneous: [email protected] C:\node_modules\mongoose-currency
Thank's a lot beforehand.
Upvotes: 0
Views: 1687
Reputation: 11
Fairly late to the party but for future folks, this is how mongoose-currency stores float values. It first multiplies by 100 and then stores it. You should divide by 100 when retrieving values. According to their readme on GitHub:
Saves a String as an integer (by stripping non-digits and multiplying by 100) to prevent rounding errors when performing calculations (See gotchas for details)
Example:
var product = new Product({ price: "$1,200.55" });
product.price; // Number: 120055
product.price = 1200;
product.price; // Number 1200 It will not round or multiply. Stored AS IS and should represent $12.00
Upvotes: 1