module.js:549抛出错误;

时间:2018-08-28 17:14:40

标签: node.js mongodb express mongoose

> module.js:549
>     throw err;
>     ^
> 
> Error: Cannot find module '..models/category'
>     at Function.Module._resolveFilename (module.js:547:15)
>     at Function.Module._load (module.js:474:25)
>     at Module.require (module.js:596:17)
>     at require (internal/module.js:11:18)
>     at Object.<anonymous> (/home/mridul/shafee-it/routes/admin.js:2:18)
>     at Module._compile (module.js:652:30)
>     at Object.Module._extensions..js (module.js:663:10)
>     at Module.load (module.js:565:32)
>     at tryModuleLoad (module.js:505:12)
>     at Function.Module._load (module.js:497:3)
>     at Module.require (module.js:596:17)
>     at require (internal/module.js:11:18)
>     at Object.<anonymous> (/home/mridul/shafee-it/server.js:74:21)
>     at Module._compile (module.js:652:30)
>     at Object.Module._extensions..js (module.js:663:10)
>     at Module.load (module.js:565:32) [nodemon] app crashed - waiting for file changes before starting...

这是我的..models / category(类别架构)

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


const CategorySchema = new Schema({
    name: { type: String, unique: true, uppercase: true}
});


module.exports = mongoose.model('Category', CategorySchema);

admin.js文件中的添加类别路由

const router = require('express').Router();
const Category = require('..models/category');

// add-category route
router.get('/add-category', function(req, res, next) {
    res.render('admin/add-category', { message: req.flash('success') });
});


router.post('/add-category', function(req, res, next) {
    var category = new Category();
    category.name = req.body.name;

    category.save(function(err) {
        if (err) return next(err);
        req.flash('success', 'Successfully added a category');
        return res.redirect('/add-category');
    });
}); 

这里的server.js文件也包含类别

const Category = require('./models/category');

app.use(function(req, res, next) {
    Category.find({}, function(err, categories) {
        if (err) return next(err);
        res.locals.categories = categories;
        next();
    });
});

const adminRoutes = require('./routes/admin');

app.use(adminRoutes);
  • 当我运行服务器或路由添加类别的url时,然后显示module.js:549 throw err;这个问题。
    这是我的问题详细信息,我在不同的时间检查我的代码。
    那我该如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

在我看来您忘记了/

  

require('..models/category');

     

require('../models/category');

这就是..models/category引发错误的原因。从一般的角度来看,当require找不到本地模块时,不要“检查代码”,只需检查文件的位置以及您编写的路径,它总是一个或另一个。 ;)