mongoose-currencies-converter v0.2.2-alpha
Mongoose currencies converter
Mongoose currencies converter is a mongoose Schema plugin that can automatically convert currency fields.
Getting started
- install the package via npm
npm install mongoose-currencies-converter- setup your mongoose model to use the plugin
const mongoose = require('mongoose');
const currenciesConverter = require('mongoose-currencies-converter');
const Schema = mongoose.Schema;
const schema = new Schema({
  price: Number,
});
schema.plugin(currenciesConverter, {
  fields: [{ name: 'price' }],
  defaultToCurrency: 'USD',
});API
Model.plugin(currenciesConverter, options)
Options are:
- fields(required) - an array of object declaring fields to convert. A field object has:- a required currency value field name
- an optional currencyfield name (if not defined conversion consider EUR)
- an optional datefield name of conversion (if not define conversion consider today)
- an optional toCurrencyconversion currency abbreviation (default is EUR)
 - Example with this configuration: - { name: 'price', currency: 'priceCurrency', date: 'createdAt', toCurrency: 'USD' }- we want to convert values inn - pricefield, whose currency is defined in- priceCurrencyfield, in- USDconsidering the date defined in the field- createdAtas the conversion date.
- a required currency value field 
- defaultToCurrency(optional) - currency abbreviation, describes currency to convert to for all fields. Default is EUR.
- convertAutomatically(optional) - allows automatic conversion before model save. Disable if you need finer control. Defaults to true
Convert On Demand
You can do on-demand conversion using the convert function
Product.findOne({ name:'Awesome product', function(err, product) {
  product.price = 99;
  product.currency = 'USD;
  product.convert(function(err, res) {
    console.log("Conversion done!");
  });
});The index method takes 2 arguments:
- options(optional) - { fields } - the fields to covert. Defaults convert all fields.
- callback- callback function to be invoked when document has been converted.
Restrictions
Mongoose
Mongoose is defined as a peer dependency so you need to install it separately.
Auto conversion
Mongoose Currencies Converter try to auto convert documents in favor of mongoose's middleware feature so conversion is fired only using document.save/Model.insertMany but not when using Model.update (as a workaround this you can do a find, modify field for this and then call this.save() or call this.update({}, { $set: { isModified: true } })).
TODO List
- Manual conversion
- Support Model.insertMany
- Handle errors
- Write example
- Add more tests
- Port to typescript