0
votes

I have created 3 files MongoDBConnect.js, booksSchema.js, Server.js and am running visualstudio.

When I run node server.js I get "Cannot find module '/booksSchema'" error. booksSchema is in the same directory as all other files.

MongoDBConnect.js

mongoose= require('mongoose')

const MONG_URI= 'mongodb://localhost:27017/BooksData'
mongoose.connect(MONG_URI,{useUnifiedTopology:true,useNewUrlParser:true, useFindAndModify:false })
const db= mongoose.connection;
db.on('error',function(err){
console.log('Error occured'+err)
})
db.once('connected',function(){
console.log('connection is successful to'+ MONG_URI)
})

module.exports=db

booksSchema.js

let mongoose= require('mongoose')
const BookScheme= new mongoose.Schema({
booktitle:{
type:String,
required:true
},
PubYear:Number,
author:String,
Topic:String,
formate:String
})

module.exports= mongoose.model('bookmodel',BookScheme,'BookCollection2')

I won't put the whole Server.js code here but here are the first lines

var express = require("express")
let Books = require('/booksSchema')
let mongodbConnected = ('/MongoDBConnect')
const cors = require('cors');

I keep getting throw err;

Error: Cannot find module '/booksSchema'

Why can't it see the booksSchema? They are all in the same directory. Any help would be appreciated

1
You need ./booksSchema, with a dot at the start. The first result for a search for "node require own files": stackoverflow.com/questions/5797852/…Chris G
Wow, such a quick response. Thank you so much. You are a star. I knew it would be something small that a newbie would have missed. Much appreciatedStepz

1 Answers

1
votes

Just so this isn't left unanswered, someone in the comments pointed out that I had missed the dot before my booksSchema path so it should have been './booksSchema' instead of '/booksSchema'.