【发布时间】:2017-12-11 02:54:27
【问题描述】:
我目前正在尝试将自定义验证器添加到我的架构中。由于某种原因,我无法查询数据库。有谁知道我的问题的解决方案?
这是架构:
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(...)
但结果是一样的。
我已经尝试了两个小时来解决这个问题,甚至尝试了不同的方法(例如 pre hook)。但是将自定义验证直接添加到 Schema 感觉就像是最干净的条目。
希望你有一个解决方案。非常感谢!
杰弗里
【问题讨论】:
-
嗯...为什么不在
slug上添加一个unique索引?尽管如此,这个answer 可能会引导您到某个地方。你试过mongoose.model('portfolio').count(...)吗? -
感谢您的回答米奇。可悲的是,这两种解决方案都不起作用。我不断收到以下错误:无法读取未定义的属性“计数”。