Home > Mobile >  Cannot find module '../models/* Trying to create REST api in Node.js and MongoDB
Cannot find module '../models/* Trying to create REST api in Node.js and MongoDB

Time:11-24

Starting out creating REST api with Node.js and Mongo DB So there is something i want to know. I am getting this Error

Cannot find module '../models/book

With the more Detailed Error as shown below :

PS D:\node_apps\mongo1> npm start

> mongo1@0.0.0 start D:\node_apps\mongo1
> node ./bin/www

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

    Error: Cannot find module '../models/book'
    Require stack:
    - D:\node_apps\mongo1\routes\users.js     
    - D:\node_apps\mongo1\app.js
    - D:\node_apps\mongo1\bin\www
        at Function.Module._resolveFilename (internal/modules/cjs/loader.js:889:15)
        at Function.Module._load (internal/modules/cjs/loader.js:745:27)
        at Module.require (internal/modules/cjs/loader.js:961:19)
        at require (internal/modules/cjs/helpers.js:92:18)
        at Object.<anonymous> (D:\node_apps\mongo1\routes\users.js:3:12)
        at Module._compile (internal/modules/cjs/loader.js:1072:14)
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
        at Module.load (internal/modules/cjs/loader.js:937:32)
        at Function.Module._load (internal/modules/cjs/loader.js:778:12)
        at Module.require (internal/modules/cjs/loader.js:961:19) {
      code: 'MODULE_NOT_FOUND',
      requireStack: [
        'D:\\node_apps\\mongo1\\routes\\users.js',
        'D:\\node_apps\\mongo1\\app.js',
        'D:\\node_apps\\mongo1\\bin\\www'
      ]
    PS D:\node_apps\mongo1> npm start
    
    > mongo1@0.0.0 start D:\node_apps\mongo1
    > node ./bin/www
    
    internal/modules/cjs/loader.js:892        
      throw err;
      ^
    
    Error: Cannot find module './routes/books'
    Require stack:
    - D:\node_apps\mongo1\app.js
    - D:\node_apps\mongo1\bin\www
        at Function.Module._resolveFilename (internal/modules/cjs/loader.js:889:15)
        at Function.Module._load (internal/modules/cjs/loader.js:745:27)
        at Module.require (internal/modules/cjs/loader.js:961:19)
        at require (internal/modules/cjs/helpers.js:92:18)
        at Object.<anonymous> (D:\node_apps\mongo1\app.js:9:15)
        at Module._compile (internal/modules/cjs/loader.js:1072:14)
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
        at Module.load (internal/modules/cjs/loader.js:937:32)
        at Function.Module._load (internal/modules/cjs/loader.js:778:12)
        at Module.require (internal/modules/cjs/loader.js:961:19) {
      code: 'MODULE_NOT_FOUND',
      requireStack: [
        'D:\\node_apps\\mongo1\\app.js',
        'D:\\node_apps\\mongo1\\bin\\www'
      ]
    }
    npm ERR! code ELIFECYCLE
    npm ERR! errno 1
    npm ERR! mongo1@0.0.0 start: `node ./bin/www`
    npm ERR! Exit status 1
    npm ERR!
    npm ERR! Failed at the mongo1@0.0.0 start script.
    npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
    
    npm ERR! A complete log of this run can be found in:
    npm ERR!     C:\Users\emi\AppData\Roaming\npm-cache\_logs\2021-11-23T17_18_24_504Z-debug.log
    PS D:\node_apps\mongo1>
    PS D:\node_apps\mongo1> 

My source code is looking thus :

Database.js

var mongoose = require('mongoose');
mongoose.connect('mongodb srv://admin:****@cluster0.cqryc.mongodb.net/test', {useNewUrlParser: true});

var conn = mongoose.connection;
conn.on('connected',function(){
    console.log('Connected');  
});

module.exports = conn;

userModel.js

var db = require('../database');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var BookSchema = new Schema({
    title : String,
    author : String,
    category : String,
});

module.exports = mongoose.model('Book',BookSchema);

users.js

var express = require('express');
var router = express.Router();
var Book = require('../models/book');


router.get('/', function(req, res) {
  Book.find({}).exec(function(err,books){
    if(err){
      res.send('error occured');
    }else{
      res.json(books);
    }
     });
});

router.get('/:id', function(req, res) {
  Book.findOne({
    _id : req.params.id
  }).exec(function(err,books){
    if(err){
      res.send('error occured');
    }else{
      res.json(books);
    }
     });
});


router.post('/',function(req,res){
  var newBook = new Book();
  newBook.title = req.body.title;
  newBook.author = req.body.author;
  newBook.category = req.body.category;
  newBook.save(function(err,book){
    if(err){
      res.send('error saving book');
    }else{
      res.send(book);
    }
  })
})

module.exports = router;

And App.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
const books = require('./routes/books');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/books', books);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});



// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});


app.use((err, req, res, next) => {
  // console.log(err);
  err.statusCode = err.statusCode || 500;
  err.message = err.message || "Internal Server Error";
  res.status(err.statusCode).json({
    message: err.message,
  });
});

module.exports = app;

What am I doing wrong? Please I need guidance. I am trying to get this to work, just missing things here.

CodePudding user response:

Below is where you are trying to find the module. you are saying that it is located in the directory outside of the one you are using to run the application here with ../

is that your intention?

var Book = require('../models/book');

Book likes like a class that's been created within your application, so if that's correct you need to locate it in the hierarchy and correctly reference it. If it's in the same location as the starting .js file then it should be:

var Book = require('./models/book');

Edit - I've just seen the export.

userModel.js

var db = require('../database');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var BookSchema = new Schema({
    title : String,
    author : String,
    category : String,
});

module.exports = mongoose.model('Book',BookSchema);

at the bottom here it looks like you're exporting this as book. I'm not a master here but whenever I export a class I reference it using

var Book = require('userModel.js')

so the .js file name.

CodePudding user response:

I got it to work. Schema=> Tables , I was referencing the very wrong Information but i got everything to work good

so instead of var Book = require('../models/book'); i ended up having this

var Book = require('../models/userModel');

and then i added this also app.use('/books', books);

and it solved all problems. Setting Cors too and everything is fine and working Correctly <3

Thanks everyone , thanks Craig!

  • Related