Saturday, 18 March 2017

Mongoose currency does not show decimals

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:

  • OS is Windows 7 32-bit
  • mongoose@4.8.6
  • node version v6.10.0 and while running npm list I got the following message (I suspect this might be the reason why I got the above problem):
npm ERR! extraneous: currency@3.0.0 C:\node_modules\currency
npm ERR! extraneous: mocha@3.2.0 C:\node_modules\mocha
npm ERR! extraneous: mongoose-currency@0.2.0 C:\node_modules\mongoose-currency

Thank's a lot beforehand.



via pattikawa

No comments:

Post a Comment