错误:找不到模块“ ./models/modela”

时间:2019-12-28 21:19:29

标签: node.js mongodb mongoose

我的应用程序有问题,文件的树是:

│   app.js
│   package-lock.json
│   package.json
│
├───models
│       modela.js
│       seedDB.js
│
└───views
    │   index.ejs
    │   landing.ejs
    │   new.ejs
    │   show.ejs
    │
    └───partials
            footer.ejs
            header.ejs

猫鼬模型出现错误

internal/modules/cjs/loader.js:800
    throw err;
    ^

Error: Cannot find module './models/modela'
Require stack:
- E:\Project\models\seedDB.js
- E:\Project\app.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:797:15)
    at Function.Module._load (internal/modules/cjs/loader.js:690:27)
    at Module.require (internal/modules/cjs/loader.js:852:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (E:\project\models\model-b.js:2:20)
    at Module._compile (internal/modules/cjs/loader.js:959:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14)
    at Module.require (internal/modules/cjs/loader.js:852:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (E:\project\app.js:6:14)
    at Module._compile (internal/modules/cjs/loader.js:959:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    'E:\\project\\models\\seed.js',
    'E:\\project\\app.js'
  ]
}

我的app.js文件由-

组成
const express  = require('express'),
    app        = express(),
    bodyParser = require("body-parser"),
    mongoose   = require("mongoose"),
    projectItem = require("./models/modela");
    seedDB = require("./models/seedDB");

seedDB();

modela组成

var mongoose   = require("mongoose");
var projectItemSchema = new mongoose.Schema({
    name: String,
    image: String,
    description: String
});
module.exports = mongoose.model("projectItem",projectItemSchema)

seedDB由

组成
const mongoose   = require("mongoose");
const Campground = require("./models/modela");

function seedDB() {
    projectItem.remove({}, function(err){
        if(err){
            console.log(err);
        }
        console.log("all projectItem removed");
    });
}

module.exports = seedDB;

谁能帮助我.. 当我在app.js(开始文件)中编写所有内容时,没有错误应用程序运行正常。 当我制作一个单独的模式模型文件时出现此问题。

1 个答案:

答案 0 :(得分:0)

在您的seedDB文件中,

const Campground = require("./models/modela");

seedDBmodela相同,但是您正在尝试从./models/modela导入它。因此,用以下代码替换上面的代码行:

const Campground = require("./modela");