为什么我的 Getter 函数不能与 Mongoose 一起使用?

问题描述 投票:0回答:2

我有一个关于我的模式的价格属性的吸气剂。 由于某种原因,当我尝试从 MongoDB 数据库查询文档时,我的 getter 函数不起作用。返回的价格值与我保存在数据库中的值完全一样,而不是通过 Math.floor(v) 得到的四舍五入数字。仅供参考,我的二传手在相同的情况下工作得很好。任何帮助将不胜感激!

 const schema = mongoose.Schema({
  name: { type: String, required: true, lowercase: true },
  isPublished: Boolean,
  author: {
    type: String,
    required: function (v) {
      return this.isPublished;
    },
    uppercase:true,
  },
  price: {
    type: Number,
    required: true,
    get: function (v) {
      return Math.floor(v);
    },
  },
});

const Documents = mongoose.model("Documents", schema);

    async function myQuery(id) {
    const result = await Documents.findById(id);
      if (!result) return debug("Not found...");
      debug(result);
    }
    
    myQuery("60348d30e7b9bf3878170955");
mongodb mongoose-schema getter
2个回答
2
投票
const schema = mongoose.Schema({
    name: { type: String, required: true, lowercase: true },
    isPublished: Boolean,
    author: {
        type: String,
        required: function (v) {
            return this.isPublished;
        },
        uppercase: true,
    },
    price: {
        type: Number,
        required: true,
        get: function (v) {
            return Math.floor(v);
        },
    },
} {
    toObject: { getters: true, setters: true },
    toJSON: { getters: true, setters: true },
    runSettersOnQuery: true
});

将以下配置添加到您的架构中并尝试一下。


0
投票

仅当您访问文档的特定属性时才应用 getter。因此,如果您按如下方式重写函数,则 getter 将应用于

price
字段:

async function myQuery(id) {
    const result = await Documents.findById(id);
    if (!result) return debug("Not found...");
    debug(result.price);
}

myQuery("60348d30e7b9bf3878170955");
© www.soinside.com 2019 - 2024. All rights reserved.