我有这个休息api:
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Post = mongoose.model('Post'),
_ = require('lodash');
/**
* Find post by id
*/
exports.post = function(req, res, next, id) {
Post.findOne({ '_id': id }, function (err, post) {
if (err) {
return next(err);
}
if (!post) {
return next(new Error('Failed to load post ' + id));
}
req.post = post;
next();
});
};
/**
* Create a post
*/
exports.create = function(req, res) {
var post = new Post(req.body);
post.save(function(err) {
if (err) {
res.jsonp(500,{ error: err.message });
} else {
res.jsonp(post);
}
});
};
/**
* Update a post
*/
exports.update = function(req, res) {
var post = req.post;
post = _.extend(post, req.body);
post.save(function(err) {
if (err) {
res.jsonp(500,{ error: err.message });
} else {
res.jsonp(post);
}
});
};
/**
* Delete a post
*/
exports.destroy = function(req, res) {
var post = req.post;
post.remove(function(err) {
if (err) {
res.jsonp(500,{ error: err.message });
} else {
res.jsonp(post);
}
});
};
/**
* Show a post by id
*/
exports.show = function(req, res) {
res.jsonp(req.post);
};
/**
* List of public posts
*/
exports.all = function(req, res) {
Post.find().sort('-created').exec(function(err, posts) {
if (err) {
res.jsonp(500,{ error: err.message });
} else {
res.jsonp(200,posts);
}
});
};
与
/* Post */
var postController = require('../app/controllers/api/post');
app.post('/api/post', postController.create);
app.get('/api/post', postController.all);
app.put('/api/post/:postId', postController.update);
app.del('/api/post/:postId', postController.destroy);
app.get('/api/post/:postId', postController.show);
/* Post Param */
app.param('postId', postController.post);
现在我需要一条其他路线 API /后/:蛞蝓
但是我不知道转向哪个方法你能给我一个提示吗? 用slug而不是id管理这个好方法吗?
像
exports.post = function(req, res, next, slug) {
Post.findOne({'slug': slug}, function (err, post) {
if (err) {
return next(err);
}
if (!post) {
return next(new Error('Failed to load post ' + slug));
}
req.post = post;
next();
});
};
答案 0 :(得分:3)
我正在做类似的事......这是我的方法......
var slugQuery = function(slug){
var query = {$or: [{slug: slug}]};
if (slug.match(/^[0-9a-fA-F]{24}$/)) {
query.$or.push({_id: slug});
}
return query;
}
exports.getProfile = function (req, res) {
var slug = req.params.slug; // Can be a slug or _id
Profile.findOne( slugQuery(slug), function(err, profile){
if(err){
// DB Error
res.status(400);
res.end();
}else if(!profile){
res.status(404);
res.end();
}else{
res.json( profile );
}
});
};
这有帮助吗?