更新:請參閱我的回答如下的最終解決方案使用對象:標題URL路徑,而不是:ID
我有一個獨特的標題名稱的對象,我想利用冠軍,而而不是整個網站的路線ID。
routes.js
// Current routing
var articles = require('../app/controllers/articles')
app.param('articleId', articles.load)
app.get('/articles', articles.index)
app.get('/articles/new', articles.new)
app.post('/articles', articles.create)
app.get('/articles/:articleId', articles.show)
app.get('/articles/:articleId/edit', articles.edit)
app.put('/articles/:articleId', articles.update)
app.del('/articles/:articleId', articles.destroy)
***
// Desired routing
app.param('articleTitle', articles.load)
app.get('/articles', articles.index)
app.get('/articles/new', articles.new)
app.post('/articles', articles.create)
app.get('/articles/:articleTitle', articles.show)
app.get('/articles/:articleTitle/edit', articles.edit)
app.put('/articles/:articleTitle', articles.update)
app.del('/articles/:articleTitle', articles.destroy)
articles.js(控制器)
exports.load = function(req, res, next, title){
Article.load(title, function (err, article) {
if (err) return next(err)
if (!article) return next(new Error('not found'))
req.article = article
next()
})
}
exports.show = function(req, res){
res.render('articles/show', {
title: req.article.title,
article: req.article
})
}
article.js(型號)
ArticleSchema.statics = {
load: function (title, cb) {
this.findOne({ title : title })
.exec(cb)
}
}
乙基本上,我已經推出了任何id引用,並將其替換爲標題引用。出於某種原因,他們根本不工作。
一個例子是將一個URL http://localhost:3000/articles/test
而不是http://localhost:3000/articles/5TheId234
,這是不行的,拋出此錯誤:GET /用品/測試404和148ms
提前感謝!
你一定有一個'article'文檔中的蒙戈數據庫標題設置爲'test'?我懷疑這是問題:'Article.load'沒有找到任何文檔,也沒有調用導致404錯誤的next()。 – Tom
你是對的,畢竟是數據。這是一箇舊的記錄使用舊的字段名稱(mongodb),所以它沒有一個標題,直到我更新它!我添加了一些額外的功能,作爲對我自己的問題的迴應,其中包括一個新的「url」字段,而不是標題。 –