how should i store a price in mongoose?

后端 未结 5 2209
再見小時候
再見小時候 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:26

    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
    });
    
    // Getter
    ItemSchema.path('price').get(function(num) {
      return (num / 100).toFixed(2);
    });
    
    // Setter
    ItemSchema.path('price').set(function(num) {
      return num * 100;
    });
    

提交回复
热议问题