2017-07-06 34 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((否則驗證程序將被忽略,因爲它沒有任何值並且不是必需的)

相關問題