【问题标题】:Required true with condition clause is not working in mongoose条件子句要求为真在猫鼬中不起作用
【发布时间】:2016-11-02 04:32:18
【问题描述】:

我正在使用猫鼬。因此,在我的一个模式中,我只想在特定字段满足条件时才将必填字段设置为 true。因此,我编写了一个函数,仅当条件为真时才将必填字段设置为真。但是即使条件错误,所需的标志也为真。甚至函数内部的控制台也没有被执行。我究竟做错了什么?提前致谢

这是我的架构

var ApplicationsSchema = new Schema({

  first_name: {
    type: String,
    required: function(value) {
        console.log('inside function')
        console.log(this.status)
         return this.status === 'submit';
     },
    validate: [validateLocalStrategyProperty, 'Please fill in the name of the Organization']
    },
     last_name: {
       type: String,
       validate: [validateLocalStrategyProperty, 'Please fill in the     name of the Organization']
     },
     phone_number: {
       type: String,
       validate: [validateLocalStrategyProperty, 'Please fill in the phone number']
   },
    status:{
   type: String,
   }
});

mongoose.model('Applications', ApplicationsSchema);

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    也许您可以添加自定义验证,而不是像这样验证必填字段,该验证仅在您选择的字段被设置时才有效。在这种情况下,您的模型看起来像

    var ApplicationsSchema = new Schema({
    
    first_name: {
        type: String,
        validate: [validateLocalStrategyProperty, 'Please fill in the name of the Organization']
    },
     last_name: {
        type: String,
        validate: [validateLocalStrategyProperty, 'Please fill in the     name of the Organization']
     },
     phone_number: {
         type: String,
         validate: [validateLocalStrategyProperty, 'Please fill in the phone number']
     },
       status:{
         type: String,
     }
    });
    
    ApplicationSchema.pre('validate', function(next){
       let _this = this;
       if(_this.status === 'submit' && !_this.first_name) { //status is submit and first name is not present -> error
          _this.invalidate("first_name", "First name is required");
          return next("first_name");
    } else { // no error
        next()
    }
    
    });
    
    mongoose.model('Applications', ApplicationsSchema);
    

    【讨论】:

    • 让我试试.. 但这里的问题是我必须将此必填字段应用于所有字段。然后我添加了所有字段的条件
    • 是的。它对我有用。但是如何为所有领域实现这一点
    • 在这种情况下,我不知道解决方案。也许你可以在服务器端代码上添加验证,甚至在尝试进入数据库之前。
    • 我在服务器端代码中做到了。请编辑返回 next("firstName");返回下一个的字段(first_name);我认为是拼写错误
    猜你喜欢
    • 1970-01-01
    • 2013-06-20
    • 2015-02-05
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    相关资源
    最近更新 更多