how should i store a price in mongoose?

后端 未结 5 2205
再見小時候
再見小時候 2020-12-14 08:48

I\'m using mongoose schemas for node.js along with express-validator (which has node-validator santiziations and validators).

What\'s a good way to store price for a

5条回答
  •  庸人自扰
    2020-12-14 09:15

    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.

提交回复
热议问题