【问题标题】:Mongoose getter is getting undefined parameterMongoose getter 正在获取未定义的参数
【发布时间】:2014-04-09 13:10:23
【问题描述】:

根据how should i store a price in mongoose? 的回答,我将价格值存储在我的 Mongoose 架构中

我的架构定义中有以下代码:

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

还有我的get函数:

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

但是,每当调用此 getter 函数时,我都可以看到未定义的 num 参数。

你知道这可能是什么原因吗?我该如何解决这个问题?

【问题讨论】:

  • 你哪里有getPrice函数?
  • 与架构定义在同一个文件中,但在定义本身之外。
  • 对于没有该字段的文档,仍会调用您的 getter 函数。在这种情况下,num 将是 undefined。这可能是你所看到的吗?
  • 事实并非如此。我检查了已经设置价格值的文件。
  • 您找到解决方案了吗?我面临同样的问题。每次我获取一个对象时,getter 方法都会运行 4 次,我不知道为什么,而且,对于这 4 次调用中的一些,我得到了未定义。

标签: javascript node.js mongodb mongoose


【解决方案1】:

为 value 添加一个默认值为零。此外,众所周知,mongoose 对不在数组中的子文档很不利,这可能会导致此问题。

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

【讨论】:

  • 刚试了一下,不幸的是它并没有解决问题。 getPrice 函数中的 num 仍然设置为 undefined。
【解决方案2】:

如果 getter/setter 给您带来 mongoose 模型的问题,请在 mongoose 架构中使用原生 static methods

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

您可以在任何具有上述架构的文档中调用该方法:

var myPrice = oneMongooseDocument.getPrice();

是一种非常干净的方法。

【讨论】:

    猜你喜欢
    • 2018-09-15
    • 2022-08-18
    • 2013-10-07
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    • 2019-11-18
    相关资源
    最近更新 更多