首页 > 解决方案 > 使用 Nodejs ExpressJS 后端通过参数查询 MongoDB 数据库时出错——

问题描述

我正在尝试查询我的 mongoDB 数据库 playerDB 并编写了一个基于 nodeJS 和 expressJS 的后端来查询数据库。让我发布相关的代码。

这是我试图在 server.js 中形成查询的部分 -->

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const PORT = 4000;
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const playerRoutes = express.Router();

app.use(cors());
app.use(bodyParser.json());

app.use(
    bodyParser.urlencoded({
        extended: false
    })
);

let Player = require('./player.model');
var query = Player.find({ player_: "Hall of Fame" });


playerRoutes.route('/hallOfFame').get(function (req, res) {
    query.exec(function (err, players) {
        if (err) {
            return handleError(err);
        }
        else {
            res.json(players);
        }
    });
});

这是我的 player.model.js --

const mongoose = require('mongoose');
const Schema = mongoose.Schema;


let Player = new Schema({
    player_name: {
        type: String
    },
    player_description: {
        type: String
    },
    player_position: {
        type: String
    },
    player_age: {
        type: String
    },
    player_club: {
        type: String
    },
    player_: {
        type: String
    },
    player_isactive: {
        type: Boolean
    },
    player_completed: {
        type: Boolean
    }
});


module.exports = mongoose.model('player', Player);

基本上我的 player_ 属性应该具有值“名人堂”,这就是我要查询的内容。那么这里的问题是什么?哪里出错了?我在名人堂周围尝试了单引号和双引号,以确保问题不存在。当我用 Postman 测试我的后端并向localhost:4000/playerDB/hallOfFame发出 GET 请求时,我只是变得空白。甚至不为空。但值得注意的一点是状态显示:200 OK

??

我完全不知所措。究竟是什么不正确?

标签: node.jsmongodbexpressnosql

解决方案


您在那里有架构,但没有架构的模型。尝试为名人堂球员制作模型。https://mongoosejs.com/docs/models.html


推荐阅读