首页 > 解决方案 > Mongoose 鉴别器忽略了一个额外的字段

问题描述

所以,我有一个Category模型,上面有三个鉴别器。其中之一,“津贴”有一个额外字段的新模式。但是,当一个新的类别被保存到数据库时,该字段将不会保存,它被猫鼬扔掉了。

const CategorySchema = new mongoose.Schema({
    name: {
        type: String,
        required: [true, "MUST HAVE A NAME"],
        validate: {
            validator: isSanitary,
            message: "NAME CONTAINS ILLEGAL CHARACTERS"
        }
    },
    amount: {
        type: Number,
        required: [true, "MUST CONTAIN AN AMOUNT"]
    },
    removed: {
        type: Boolean,
        default: false
    }
}, {discriminatorKey: "kind"});
const Category = mongoose.model("Category", CategorySchema);

Category.discriminator("Income", new mongoose.Schema());

Category.discriminator("Bill", new mongoose.Schema());

Category.discriminator("Allowance",
    new mongoose.Schema({
        isPercent: {
            type: Boolean,
            required: true
        }
    })
);

module.exports = {
    Income: Income,
    Bill: Bill,
    Allowance: Allowance,
    CategorySchema: CategorySchema
};

要求型号:

const {Income, Bill, Allowance} = require("../models/category.js");

创建新类别的代码:

/*
    POST: create a new Category
    req.body = {
        account: String (Account id)
        name: String
        amount: Number
        kind: String (Income, Bill, Allowance)
        isPercent: Boolean
    }
    response: Category
    */
    createCategory: function(req, res){
        let category = {
            name: req.body.name,
            amount: req.body.amount,
            removed: false
        };

        switch(req.body.kind){
            case "Income":
                category = new Income(category);
                break;
            case "Bill":
                category = new Bill(category);
                break;
            case "Allowance":
                category = new Allowance(category);
                category.isPercent = req.body.isPercent;
                break;
        }

        res.locals.user.accounts.id(req.body.account).categories.push(category);

        res.locals.user.save()
            .then((user)=>{
                return res.json(category);
            })
            .catch((err)=>{
                console.error(err);
                return res.json("ERROR: unable to create new category");
            });
    },

当一个新的“津贴”被保存时,它保存得很好,除了isPercent没有保存到数据库中。这以前是有效的,但是当我做了一个微小的改变时就停止了。唯一的变化是我开始导出模式和模型。我什至不知道如何调试这个问题。

谢谢你的帮助。

标签: javascriptmongodbmongoosediscriminator

解决方案


问题是您将Category模型视为与Allowance类别鉴别器模型相同。你不能保存isPercentCategory,只有Allowance。请注意,在文档中,当他们想要创建鉴别器模型时,他们不使用基础,而是使用鉴别器。尝试导出鉴别器模型:

const Income = Category.discriminator("Income", new mongoose.Schema());
const Bill = Category.discriminator("Bill", new mongoose.Schema());
const Allowance = Category.discriminator("Allowance",
    new mongoose.Schema({
        isPercent: {
            type: Boolean,
            required: true
        }
    })
);

module.exports = {
    CategorySchema,
    Category,
    Income,
    Bill,
    Allowance,
};

然后,您可以更新路由处理程序中的逻辑以有条件地创建Allowanceor Category

const { Allowance, Category } = require("../models/category");
 
// ...    

// Get correct model based on req.body data
const Model = req.body.kind === "Allowance" ? Allowance : Category;
let category = new Model({
  name: req.body.name,
  amount: req.body.amount,
  kind: req.body.kind,
  isPercent: req.body.kind === "Allowance" ? req.body.isPercent : undefined,
});

希望这会有所帮助!


推荐阅读