我目前正在嘗試將自定義驗證程序添加到我的模式中。出於某種原因,我無法查詢數據庫。有誰知道我的問題的解決方案?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感覺就像是最乾淨的條目。
希望你對我有一個解決方案。提前謝謝了!
傑弗裏
嗯......爲什麼不在'slug'上添加一個'unique'索引?儘管如此,這個[answer](https://stackoverflow.com/a/14271900/1022914)可能會指引你。你有沒有試過'mongoose.model('portfolio')。count(...)'? – Mikey
謝謝你的回答Mikey。可悲的是,這兩種解決方案都無效。我不斷收到以下錯誤:無法讀取未定義的屬性'count'。 – Jeffrey