how should i store a price in mongoose? how should i store a price in mongoose? mongoose mongoose

how should i store a price in mongoose?


This is what I ended up doing...

I stored price as cents in database, so it is 4999 for 49.99 as described here: https://dba.stackexchange.com/questions/15729/storing-prices-in-sqlite-what-data-type-to-use

the getPrice will convert it back to readable format, so I can use item.price in my views w/o modifying it.

the setPrice converts it to cents.

model:

var ItemSchema = new Schema({    name            : { type: String, required: true, trim: true }    , price             : {type: Number, get: getPrice, set: setPrice }});function getPrice(num){    return (num/100).toFixed(2);}function setPrice(num){    return num*100;}

I opted to only allow digits and decimal in price field, without $.So they can enter 49, 49.99, 49.00, but not 49.0 or $49

validation using regex:

if ( req.body.price ) {    req.assert('price', 'Enter a price (numbers only)').regex(/^\d+(\.\d{2})?$/);}

I wish there was a way to allow the $ because I think its a usability issue, just let the user enter it, but strip it off. I'm not sure how to do that and still validate that we have a price and not a bunch of letters for example.


Hint: The method described here is basically just another implementation of chovy's answer.

Workaround for Mongoose 3 & 4:

If you have trouble to define getters and setters directly in the schema, you could also use the schema.path() function to make this work:

var ItemSchema = new Schema({  name: String,  price: Number});// GetterItemSchema.path('price').get(function(num) {  return (num / 100).toFixed(2);});// SetterItemSchema.path('price').set(function(num) {  return num * 100;});


Adds schema type "Currency" to mongoose for handling money. Strips out common characters automatically (",", "$" and alphabet chars)

https://github.com/paulcsmith/mongoose-currency

What it does:

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)Strips out symbols from the beginning of strings (sometimes users include the currency symbol)Strips out commas (sometimes users add in commas or copy paste values into forms, e.g. "1,000.50)Only save from two digits past the decimal point ("$500.559" is converted to 50055 and doesn't round)Strips [a-zA-Z] from stringsPass in a string or a number. Numbers will be stored AS IS.Assumes that if you set the value to an integer you have already done the conversion (e.g. 50000 = $500.00)If a floating point number is passed in it will round it. (500.55 -> 501). Just pass in integers to be safe.

Hope it helps some1.