2017-07-06 45 views
0

我目前正在尝试将自定义验证程序添加到我的模式中。出于某种原因,我无法查询数据库。有谁知道我的问题的解决方案?Mongoose自定义验证程序:检查数据库中是否存在值

这是架构:

var Portfolio = new Schema({ 
    title: { 
     type: String, 
     required: [true, 'Title is required'] 
    }, 
    thumbnail: { 
     type: String, 
     required: [true, 'Thumbnail is required'], 
    }, 
    description: String, 
    date: Date, 
    images: [String], 
    categories: [Schema.Types.ObjectId], 
    order: Number, 
    slug: { 
     type: String, 
     validate: { 
      validator: slugExists, 
      message: 'Slug already exists, choose a different title', 
     } 
    } 
}, options); 

这是检查是否存在数据的方法:

function slugExists(value) { 
    this.model.count({slug: value}, function(err, count) { 
     if (error) { 
      return err; 
     } 
     return count > 0; 
    }); 
} 

当我运行的应用程序,我得到了以下错误消息:

TypeError: this.model.count is not a function 

我也试过使用以下内容:

mongoose.model['portfolio'].count(...) 

但结果是一样的。

我一直试图解决这个问题两个小时,甚至尝试了不同的方法(例如预钩)。但直接添加自定义验证到Schema感觉就像是最干净的条目。

希望你对我有一个解决方案。提前谢谢了!

杰弗里

+0

嗯......为什么不在'slug'上添加一个'unique'索引?尽管如此,这个[answer](https://stackoverflow.com/a/14271900/1022914)可能会指引你。你有没有试过'mongoose.model('portfolio')。count(...)'? – Mikey

+0

谢谢你的回答Mikey。可悲的是,这两种解决方案都无效。我不断收到以下错误:无法读取未定义的属性'count'。 – Jeffrey

回答

0

可以使用pre-save方法 考虑下面其中试图在用户模型来验证用户名的例子:

UserSchema.pre('save', function (next) { 
    var self = this; 
    mongoose.models["User"].findOne({username: self.username}, function (err, user) { 
     if (!user) { 
      next(); 
     } else { 
      next(new Error("Username already exists!")); 
     } 
    }); 
+0

感谢您提出解决方案。我不想用pre钩子,因为那时我必须想办法处理错误信息(正如你可以在我的例子中看到的,我使用Mongoose的自定义消息来处理错误)。 – Jeffrey

+0

通过使用上面也你得到相同的自定义错误。您也可以在自定义功能中使用挂钩功能。 –

+0

谢谢你的回复。最终我找到了我正在寻找的解决方案。不过,我很好奇你如何在预钩子中构建相同的自定义错误。我会考虑的! – Jeffrey

0

虽然我是测试不同的解决方案,我发现,回答我的问题后(https://stackoverflow.com/a/26268156/8267696)。

这就是我一直在寻找的解决方案:

function slugExists(value, callback) { 
    this.constructor.count({slug: value}, function(err, count) { 
     if (err) { 
      next(err); 
     } 
     callback(count === 0); 
    }); 
} 

Portfolio.pre('validate', function(next) { 
    this.slug = slugify(this.title); 
    next(); 
}); 

边注:团状将根据标题生成。这就是为什么我必须使用'验证'前钩子,以便在验证之前已经设置了slu((否则验证程序将被忽略,因为它没有任何值并且不是必需的)

相关问题