【问题标题】:Retrieve an object from collection by its name using nodejs使用nodejs按名称从集合中检索对象
【发布时间】:2016-07-10 20:14:13
【问题描述】:

所以我目前正在使用 MEAN 堆栈制作应用程序。我目前遇到的问题是,在调用 API 时,我能够成功地从数据库中检索所有对象和每个对象的 ID(使用 POSTMAN(Chrome))我使用猫鼬和快递路由器设置。我的问题是,我可以通过名称检索对象吗?我一直在网上搜索,但我不确定如何实现这一点。例如:这是我目前拥有的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) 进行 api 调用并返回相关的菜。任何帮助将不胜感激。

【问题讨论】:

    标签: angularjs node.js express mongoose mean-stack


    【解决方案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);
        });
    });
    

    【讨论】:

    • 不幸的是,我在查询 url "localhost:3000/api/dishes/Eggs Benedict" 之前尝试过这个,这就是返回的内容:'code' { "message": "Cast to ObjectId failed for value \" Eggs Benedict\" at path \"_id\"", "name": "CastError", "kind": "ObjectId", "value": "Eggs Benedict", "path": "_id" }
    • 相同的结果,似乎是指仍然链接到对象_id的路径。 ""message": "在路径 \"_id\"" 的值 \"Eggs Benedict\" 中转换为 ObjectId 失败?
    • 实际上这里的请求正在访问 apiRouter.get('/dishes/:_id) 并且在那个处理程序中你试图通过 id Dishes.findById(req.params._id) 和 whcih 找到它正在尝试将 Eggs 值转换为 id 并抛出 Cast 错误
    • 你可以在这里做什么你可以twick你的api,我已经编辑了
    • 工作就像一个魅力!非常感谢:)
    猜你喜欢
    • 2014-03-03
    • 2022-11-13
    • 2020-09-01
    • 1970-01-01
    • 2013-05-11
    • 2018-12-31
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多