【问题标题】:Express.js Type Error When Importing DB Schema导入数据库架构时 Express.js 类型错误
【发布时间】:2020-04-10 22:29:07
【问题描述】:

在 MEAN 堆栈上创建一个小型 Web 应用程序,我正在将我的架构迁移到单独的“模型”目录。当架构在同一个 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 文件中时完全可以正常工作,但在导入时就不行了。我在这里想念什么?提前感谢您的帮助。

【问题讨论】:

    标签: node.js express mean-stack


    【解决方案1】:

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

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

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

    / 表示回到根目录,然后向前/向下遍历。

    ./ 表示从我们当前所在的文件夹开始,向前/向下遍历

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

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

    【讨论】:

    • 请原谅我,这应该读成复数形式,结尾有一个“S”,这不是问题所在。话虽如此,您的第二个建议是正确的。我的模型目录不在我认为的位置,对它的引用结果证明是问题所在。
    猜你喜欢
    • 2011-09-15
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多