简体   繁体   English

验证不起作用猫鼬

[英]Validation not working mongoose

Im using Monggose 4.8.1.我使用的是 Monggose 4.8.1。 I have a simple schema:我有一个简单的架构:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var Organisation = new mongoose.Schema({
  name: {
    type: String,
    required: [true, 'Organisation name must be provided'],
    unique: [true, 'Organisation name must be unique']
  },
  createdBy: { 
    type: String, 
    ref: 'User'
  },
  createdOn: {
    type: Date,
    "default": Date.now
  },
  availableUntil: {
    type: Date
  }
});

mongoose.model('Organisation', Organisation);

I've already saved the email email@domain.com in the document.我已经将电子邮件 email@domain.com 保存在文档中。

Now I want to try saving it again and first check that its valid using validateAsync .现在我想再次尝试保存它并首先使用validateAsync检查它是否有效。 So i expect to get an error because the email is not unique.所以我希望得到一个错误,因为电子邮件不是唯一的。

var organisation = new Organisation({
    name: 'email@domain.com'
});

var validResult = organisation.validateSync();

console.log('validResult is ', validResult);

But validResult is always undefined ...但是 validResult 总是undefined的......

EDIT编辑

I added an extra attribute to my schema:我在我的架构中添加了一个额外的属性:

  eggs: {
    type: Number,
    min: [6, 'Too few eggs'],
    max: 12
  }

And then tried to save eggs: 3 and this produced an error.然后试图保存eggs: 3 ,这产生了一个错误。 So bizarrely, mongoose validation does not seem to check if a value is unique or not, even when set in the schema...奇怪的是,猫鼬验证似乎并没有检查一个值是否唯一,即使在模式中设置......

Mark.标记。

Could you verify that mongodb has record for your saved model: db.organisations.find() ?您能否验证 mongodb 是否有您保存的模型的记录: db.organisations.find()

it looks like if you have undefined value it means the document had passed validation steps by following the documentation for validateSync() :看起来如果您有undefined的值,则意味着文档已按照validateSync()的文档通过了验证步骤:

  var err = doc.validateSync();
  if ( err ){
    handleError( err );
  } else {
    // validation passed
  }

For this type of validation you can follow this process using path and validate .对于这种类型的验证,您可以使用pathvalidate遵循此过程。

in schema在模式中

var OrganisationSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, 'Organisation name must be provided']
  }
 //....
});


OrganisationSchema.path('name').validate(function(value, done){
  var self = this;
  if(!self.isNew){
    return done(true);
  }else{
   //mongoose.models['Organisation'] or self.model('Organisation')
    mongoose.models['Organisation'].count({name: value}, function(err, count){
      if(err){
        return done(err);
      }

      return done(!count)
    });
  }
}, "This email already exists" );


mongoose.model('Organisation', OrganisationSchema);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM