【问题标题】:How to make mongoose schema dynamic, depending upon the value?如何根据值使猫鼬模式动态化?
【发布时间】:2021-05-10 17:16:52
【问题描述】:

我是猫鼬的新手,我已经搜索了很多关于它的内容,但无法找到答案。请帮忙,提前谢谢。

const user = new mongoose.Schema({
    email: {
        type: String,
        required: true,
        unique: true
    },
    rollno: {
        type: Number,
        required: true,
        unique: true,
        
    },
    password : {
        type: String,
        required: true,
    },
    isVoter: {
        type: Boolean,
        required: true,
        default: true
    }
}, {
    timestamps: true
});

我能否有一个依赖于 isVoter 值的架构。例如,如果 isVoter 的值为 false 那么我们应该有这样的架构:

const user = new mongoose.Schema({
    email: {
        type: String,
        required: true,
        unique: true
    },
    rollno: {
        type: Number,
        required: true,
        unique: true,

    },
    password : {
        type: String,
        required: true,
    },
    isVoter: {
        type: Boolean,
        required: true,
        default: true
    },
    promises: [
        {
           type: String
        }
    ]
    , {
    timestamps: true
});

【问题讨论】:

    标签: javascript node.js database mongoose dynamic-schema


    【解决方案1】:

    您可以通过这种方式定义一个变量是required 还是不基于另一个属性:

    promises: [
            {
               type: String,
               required: function(){
                 return this.isVoter == false
               }
            }
        ]
    

    因此,仅当 isVoter 为 false 时才需要 promises。否则不需要。

    【讨论】:

    • isVotertrue 时,我不希望架构中出现 promises。即使 isVotertrue,您的解决方案也允许添加 promises
    • 设置 false insetad of true。无论如何,如果这不是所需的行为,请尝试更好地解释问题。
    • 其实我希望如果一个人是选民,这意味着isVoter == true,那么他/她就不会做出任何承诺,这意味着没有人不应该当他/她是选民时,能够添加承诺。但是您的解决方案表明,尽管 isVoter == true,仍然可以添加承诺。
    【解决方案2】:

    你可以在猫鼬中使用pre钩子,检查documentation并在保存之前检查isVoter的值,如果你不想保存承诺,试试this.promises = undefined

    user.pre('save',  function(next) {
        if(this.isVoter== true){
           this.promises = undefined
        }
        else{
          this.promises = "hello"
          //do somethings
        }
       next();
    });
    

    并且应该在模式中定义承诺

    【讨论】:

      猜你喜欢
      • 2015-03-25
      • 2017-12-25
      • 2019-02-23
      • 2014-06-01
      • 2021-09-22
      • 1970-01-01
      • 2017-06-26
      • 2016-12-26
      相关资源
      最近更新 更多