所以我目前使用MEAN堆栈制作应用程序。我目前的问题是,当调用API时,我能够通过数据库中的ID成功检索所有对象和每个对象(使用POSTMAN(Chrome))我使用mongoose&快递路由器。我的问题是,我可以通过它的名字检索一个对象吗?我一直在网上搜索,我不确定如何实现这一点。例如:这是我目前拥有的Api代码。
var Dishes = require('../../app/models/dishes');
var Terms = require('../../app/models/terms');
var config = require('../../config');
module.exports = function(app,express){
// api ---------------------------------------------------------------------
var apiRouter = express.Router();
// middleware to use for all requests
apiRouter.use(function (req, res, next) {
// do logging
console.log('Somebody just came to our app!');
next();
});
// Test routes to make sure everything is working
//(accessed at GET http://localhost:3000/api)
apiRouter.get('/', function (req, res) {
res.json({message: 'Welcome to the API!'});
});
/** ================================= Dishes ==========================================**/
//on routes that end in /dishes , show all dishes in json
apiRouter.get('/dishes', function (req, res) {
Dishes.find(function (err, dishes) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err)
res.send(err);
res.json(dishes); // return all dishes in JSON format
});
});
//on routes that end in /dishes/:_id , show all the this with the corresponding ID
// get the dish with that id
// (accessed at GET http://localhost:8080/api/dishes/:dish_id)
apiRouter.get('/dishes/:_id',function(req, res) {
Dishes.findById(req.params._id, function(err, dish) {
if (err) res.send(err);
// return that dish
res.json(dish);
});
});
return apiRouter;
};
我访问的菜模型如下:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//with Mongoose everything is derived from a schema ! Lets get a reference and define our Dishes Schema
var DishSchema = mongoose.Schema({
dishName: {type: String, index: {unique: true}},
Desc : {type: String, index: { unique: true}},
Allergy: String,
HealthRisks: String
},{collection:'Dishes'});
module.exports = DishSchema;
//The Next step is to compile our schema into a model
var Dishes = mongoose.model('Dishes', DishSchema);//Dish Schema into model
// return the model
module.exports = mongoose.model('Dishes', DishSchema)
我想做的是打电话给(/ dishes /:dishName)并返回相关的菜肴。任何帮助将不胜感激。
答案 0 :(得分:1)
apiRouter.get('/dishes/getByName/:dishName',function(req, res) {
Dishes.findOne({dishName:req.params.dishName}, function(err, dish) {
if (err) res.send(err);
// return that dish
res.send(dish);
});
});