繁体   English   中英

API(NodeJS + Express)中未显示数据

[英]Data not showing in the API (NodeJS + Express)

我正在为想要通过输入餐厅名称检索餐厅数据的餐厅开发示例 API。 Controller,Model & 路由器已设置,但如果我将其加载到 Postman 数据不会出现。 请分享一些想法。

Controller:(restaurant.js)

const restaurants = require('../Models/restaurantData');
exports.getRestaurantName = (req, res) => {
    const Name = req.params.name;    
    restaurants.find({
        name: Name
    }).then(result => {
        res.status(200).json({
            message: "Restaurant Data",
            restaurants: result[0]
        });
    }).catch(error => {
        res.status(500).json({
            message: error
        });
    });
}

Model: (restaurantData.js)

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const restaurantSchema = new Schema({
    _id: {
        type: Number,
        required: true
    },
    name: {
        type: String,
        required: true
    },
    city_name:{
        type: String,
        required: true
    },
    city_id: {
        type: String,
        required: true
    },
    location_id: {
        type: Number,
        required: true
    },
    area: {
        type: Number,
        required: true
    },
    locality:{
        type: String,
        required: true
    },
    thumb: {
        type: String,
        required: true
    },
    cost:{
        type: Number,
        required: true
    },
    address:{
        type: String,
        required: true
    },
    mealtype:{
        type: Number,
        required: true
    },
    name:{
        type: String,
            required: true
        },    
    cuisine:{
        type: Number,
        required: true
    },
    type:{
        type: Array,
        required: true
    },
    Cuisine:{
        type: Array,
        required: true
    }
});

module.exports = mongoose.model('restaurantData', restaurantSchema, 'restaurantData');

路由器:

const express = require('express');
const restaurantController = require('../Controllers/restaurant');

const router = express.Router();

router.get('/restaurantData/:name',restaurantController.getRestaurantName);

module.exports = router;

更改以下内容,我希望它会起作用。 在餐厅 Model 中,删除此:

module.exports = mongoose.model(  "restaurantData",  restaurantSchema,  "restaurantData");

并添加:

const Restaurant = mongoose.model("restaurantData", restaurantSchema);
module.exports = { Restaurant };

在您的餐厅 controller 中,将导入脚本更改为:

const { Restaurant } = require("../Models/restaurantData");

方法将是:

Restaurant.find({
    name: Name,
  })

根据需要更改变量和文件名。

如果是,您是否添加了网络访问权限,然后使用Model.create(req.body(err,data)={ res.send(data); })

我认为问题可能出在从架构中创建 model 时

module.exports = mongoose.model('restrauntData', restaurantSchema);   

使用上面的而不是

module.exports = mongoose.model(  "restaurantData",  restaurantSchema,  "restaurantData");

那么它应该可以正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM