首页 > 解决方案 > 为什么我的 Getter 函数不能与 Mongoose 一起使用?

问题描述

我对我的模式的价格属性有一个吸气剂。出于某种原因,当我尝试从 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");

标签: mongodbmongoose-schemagetter

解决方案


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
});

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


推荐阅读