繁体   English   中英

自定义验证器,cb不是函数

[英]Custom validator, cb is not a function

使用猫鼬在node.js中使用自定义验证器的问题。 我正在尝试在插入query之前检查headerLog是否存在query

我的代码如下:

var mongoose = require('mongoose'); //layer above mongodb
var Schema = mongoose.Schema;

var headerLogSchema = new Schema({
    query: { type: String, required: true, unique: true, validate: {
          validator: function(v, cb) {
            HeaderLog.find({query: v}, function(err, documents){
               cb(documents.length == 0);
            });
          },
          message: 'Header already exists in log, didnt save this one.'
        }
    }
})

var HeaderLog = mongoose.model('headerLog', headerLogSchema);

module.exports = HeaderLog;

错误: TypeError: cb is not a function

我这样调用此函数:

function logHeader(query) {
  var newHeaderLog = new HeaderLog({
    query: query
  })

  newHeaderLog.save(function(err) {
    if (err) {
      console.log(err);
    }
    else {
      console.log('New header logged');
    }
  });
}

我究竟做错了什么?

如果您在doc中查看异步验证器示例,则似乎必须传递选项isAsync: true才能告诉猫鼬您正在使用异步验证器,因此应向其传递回调。

var headerLogSchema = new Schema({
    query: { 
       type: String, 
       required: true, 
       unique: true, 
       validate: {
          isAsync: true,                   // <======= add this
          validator: function(v, cb) {
            HeaderLog.find({query: v}, function(err, documents){
               cb(documents.length == 0);
            });
          },
          message: 'Header already exists in log, didnt save this one.'
        }
    }
})

作为参考状态,异步验证器应具有isAsync标志:

validate: {
  isAsync: true,
  validator: function(v, cb) { ... }
}

或兑现承诺。 由于验证者已经使用了另一个模型,并且Mongoose模型是基于承诺的,因此使用现有的promise是有意义的:

  validator: function(v) {
    return HeaderLog.find({query: v}).then(documents => !documents.length);
  }

countDocuments是一个更好的选择,以find案件计数只需要文档时。

暂无
暂无

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

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