简体   繁体   中英

Mongoose getter is getting undefined parameter

I'm storing a price value in my Mongoose schema according to the answer from how should i store a price in mongoose?

I have the following code in my schema definition:

 price: {
        value: {
            type: Number,
            get: getPrice,
            set: setPrice,
            min: 0
        },
        currency: {
            type: String,
            default: 'PLN',
            trim: true,
            enum: ['PLN', 'EUR']
        }
},

and my get function:

function getPrice(num){
    return (num/100).toFixed(2);
}

However, whenever this getter function is called I can see that the num parameter in undefined.

Do you know what might be the reason for that? And how could I fix this?

Add a default of zero for value. Also, mongoose is notoriously bad about subdocuments that are not inside an array, which may be causing this problem.

    value: {
        type: Number,
        get: getPrice,
        set: setPrice,
        min: 0,
        default: 0
    },

If getter/setters give you problems with mongoose models, use the native static methods in mongoose schemas:

mySchema.static('getPrice', function(){
    //'this' in the context means a document that shares the schema
    return (this.price.value/100).toString(2); 
});

You can invoke the method in any document that have said schema:

var myPrice = oneMongooseDocument.getPrice();

Is a very clean approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM