Express.js 导入数据库架构时出现类型错误

Express.js Type Error When Importing DB Schema

在 MEAN 堆栈上创建一个小型 Web 应用程序,我正在将我的架构迁移到单独的 "models" 目录。当模式在同一个 app.js 文件中定义时,一切正常;然而,当我将代码切换到一个单独的更模块化的文件并导入它时,我得到了这个错误:

TypeError: Player.find is not a function
at /Users/username/code/express/WebApp/v3/app.js:57:12

当它到达需要查找玩家的第一条路线时会发生此错误,我不太确定在盯着它看了几个小时后我错过了什么。

我的 app.js 文件:

var express    = require("express"),
    app        = express(),
    bodyParser = require("body-parser"),
    mongoose   = require("mongoose"),
    Player     = require("./models/players")

const port     = 3000;

mongoose.connect("mongodb://localhost/players", { useNewUrlParser: true, useUnifiedTopology: true });
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended: true}));


// PLAYER SCHEMA ORIGNALLY DEFINED HERE BUT NOW ATTEMPTING TO MOVE TO DIFF DIRECTORY & IMPORT
/*var playerSchema = new mongoose.Schema({
    player: String,
    position: String,
    description: String
});
var Player = mongoose.model("Player", playerSchema);*/

app.get("/", function(req, res) {
    res.render("landing");
});

app.get("/players", function(req, res) {
    // Get all players from DB
    Player.find({}, function(err, allPlayers){
        if(err){
            console.log(err);
        } else {
            console.log("We're good.");
            res.render("players", {players: allPlayers});        
        }
    });
});

和我正在尝试导入的 player.js 文件:

var mongoose   = require("mongoose");

var playerSchema = new mongoose.Schema({
    player: String,
    position: String,
    description: String
});


// Compile into a model
module.exports = mongoose.model("Player", playerSchema);

上述模式定义和模型定义在 app.js 文件中时完全正常,但在导入时则不然。我在这里错过了什么?在此先感谢您的帮助。

我认为您的文件名在 require 语句中是错误的。它的

const Player = require('../models/player')

因为您的文件名是 player.js,而不是 players.js,并且如果您将 js 文件存储在模型文件夹中。请检查如何使用文件路径导航

/表示回到根文件夹,然后遍历forward/downward.

./ 表示从我们当前所在的文件夹开始遍历 forward/downward

../ 表示上一级目录,然后开始遍历。

而且你的后端应该是这样的。 Backend File Management