2016-03-23 3 views
1

, поэтому Im в настоящее время создает приложение с использованием стека MEAN. Проблема, на мой взгляд, заключается в том, что при обращении к API я могу успешно извлечь все объекты и каждый объект по ID из базы данных (используя POSTMAN (Chrome)). Я настроил с помощью mongoose & express router. Мой вопрос: могу ли я получить объект по его имени? Я искал в Интернете, и я не уверен, как это реализовать. Например: это код Api, который у меня есть.Извлечь объект из коллекции по его имени с помощью nodejs

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) 

То, что я хочу сделать, это сделать апи вызов (/ блюдо /: dishName) и возвращают соответствующее блюдо. Любая помощь будет принята с благодарностью.

ответ

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); 
    }); 
}); 
+0

К сожалению, я попытался это раньше, и на запросе URL «HTTP: // локальный: 3000/API/блюда/Яйца Бенедикт», это то, что возвращается: «код» { «сообщение»: " «CastIrror», «вид»: «ObjectId», «значение»: «Яйца Бенедикт», «Знак»: «Яйца Бенедикт», «имя»: «CastError», «path»: «_id» } –

+0

проверить отредактированный ответ – RootHacker

+0

Тот же результат, похоже, ссылается на путь, все еще связанный с _id объекта. «сообщение»: «Не удалось ли передать объект ObjectId для значения» «Яйца Бенедикт» на пути \ "_ id \" "? –

Смежные вопросы