How do I fix this error? Mongooseconnection error - node.js

I am trying to run my application and it keeps giving me this error and this is from a demo app from sitepoint. This is the details of the app
https://www.sitepoint.com/build-simple-beginner-app-node-bootstrap-mongodb/
The error:
throw new MongooseError('The `uri` parameter to `openUri()` must be a ' +
^
MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mo
ngoose.connect()` or `mongoose.createConnection()` is a string.
at new MongooseError (C:\Users\tychi\WebstormProjects\demo-node-app\node_modules\mongoose\lib\error\mongooseError.js:
10:11)
at NativeConnection.Connection.openUri (C:\Users\tychi\WebstormProjects\demo-node-app\node_modules\mongoose\lib\conne
ction.js:579:11)
at Mongoose.connect (C:\Users\tychi\WebstormProjects\demo-node-app\node_modules\mongoose\lib\index.js:333:15)
at Object.<anonymous> (C:\Users\tychi\WebstormProjects\demo-node-app\start.js:4:10)
at Module._compile (internal/modules/cjs/loader.js:688:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
at Module.load (internal/modules/cjs/loader.js:598:32)
at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
at Function.Module._load (internal/modules/cjs/loader.js:529:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:741:12)
at startup (internal/bootstrap/node.js:285:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:739:3)
[nodemon] app crashed - waiting for file changes before starting...
the code:
require('dotenv').config();
const mongoose = require('mongoose');
mongoose.connect(process.env.demoapp ,
{ useNewUrlParser: true },
{ useUnifiedTopology: true })
mongoose.connection
.on('open', () => {
console.log('Mongoose connection open');
})
.on('error', (err) => {
console.log(`Connection error: ${err.message}`);
});
require('./models/Registration');
const app = require('./app');
const server = app.listen(3000, () => {
console.log(`Express is running on port ${server.address().port}`);
});

Related

Cannot read property 'connect' of undefined in env file

const dotenv = require('dotenv');
const { mongoose } = require('mongoose');
// const bodyParser = require('body-parser');
const app = express();
app.use(express.json());
const DB = `mongodb+srv://${process.env.MONGO_DB_USER}:${process.env.MONGO_DB_PASSWORD}#cluster0.70g8h.mongodb.net/${process.env.MONGO_DB_DATABASE}?retryWrites=true&w=majority`
mongoose.connect( DB ,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
})
.then( ()=>console.log('Connection Success ..'))
.catch( (err)=>console.log(' Not Connection Success'));
dotenv.config({path:'./config.env'});
app.get('/', (req, res,next) => {
res.status(200).json({
message:'Hello'
});
});
app.post('/data', (req, res,next) => {
res.status(200).json({
message: req.body
});
});
app.listen(process.env.PORT,()=>{
console.log(`Server is runing at the port : ${process.env.PORT}`);
})
Getting this error when using this code, I would like to know what is causing the error and any possible fixes. I am using atlas MongoDB
this is the output
D:\WebDevelopment.Ravi\Projects\mern_ecommerce\e-commerce-backend\src\index.server.js:9
mongoose.connect( DB ,
^
TypeError: Cannot read property 'connect' of undefined
at Object.<anonymous> (D:\WebDevelopment.Ravi\Projects\mern_ecommerce\e-commerce-backend\src\index.server.js:9:10)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
[nodemon] app crashed - waiting for file changes before starting..
Getting this error when using this code, I would like to know what is causing the error and any possible fixes. I am using atlas MongoDB
From ths docs Getting Started. It should be const mongoose = require('mongoose');
Try this, it should work:
const mongoose =require("mongoose");
require('dotenv').config();

NodeJS: Error: Cannot find module '/models/filename' after having renamed it

I am still relatively new to NodeJS. Now I encounter this problem: I had a file called "./models/route" I renamed it by changing the filename in VS Code to: "./models/routes". I then changed that name in all of the scripts. I checked, doubledchecked, triplechecked and quadruplechecked that it has been changed everywhere and it has.
Now I get this error in the console:
internal/modules/cjs/loader.js:638
throw err;
^
Error: Cannot find module './models/routes'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
at Function.Module._load (internal/modules/cjs/loader.js:562:25)
at Module.require (internal/modules/cjs/loader.js:690:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (C:\node-projects\wandelverhalen\controllers\routesController.js:4:16)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:690:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (C:\node-projects\wandelverhalen\index.js:11:26)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
[nodemon] app crashed - waiting for file changes before starting..
The error apparently is encountered in internal/modules/cjs/loader.js:638. So it does not point me to a script that I made or can change.
I really am at a loss...
Edit:
As Mosifa points out in his comment the error points to ./wandelverhalen/controllers/routesController.js and ./wandelverhalen/index.js.
Here are the scripts. I still can't find the problem.
index.js:
"use strict";
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const Routes = require("./models/routes");
const homeController = require("./controllers/homeController");
// const errorController = require("./controllers/errorController");
const routesController = require("./controllers/routesController");
mongoose.connect("mongodb://localhost:27017/db_wandelen", {
useNewUrlParser: true
});
const db = mongoose.connection;
db.once("open", () => {
console.log("Connected to MongoDB");
});
app
.set("port", process.env.PORT || 3000)
.set("view engine", "ejs")
.use(
express.urlencoded({
extended: false
})
)
.use(express.json())
.use(express.static("static"))
.use(layouts)
.use((req, res, next) => {
console.log(`Request made to ${req.url}`);
next();
})
// .use(errorController.pageNotFoundError)
// .use(errorController.internalServerError)
.get("/", homeController.start)
.get("/kempen", homeController.kempen)
.get("/rivieren", homeController.rivieren)
.get("/oost_belgie", homeController.oost_belgie)
.listen(app.get("port"), () => {
console.log(`Server running at port ${app.get("port")}`);
});
routesController.js:
"use strict";
const mongoose = require("mongoose");
const Routes = require("./models/routes");
exports.getAllRoutes = (req, res, next) => {
Routes.find({}, (error, routes) => {
if (error) next(error);
req.data = routes;
next();
});
};

Error: listen EADDRINUSE: address already in use :::6000

i have started my server many times like 4000 5000 6000 but getting same answer, on my port throw er; // Unhandled 'error' event i dont know why i have changed it many times , i also kill my server with ctrl c and then re started but get same error Error: listen EADDRINUSE: address already in use :::6000
const express = require('express');
const app = express();
const Joi = require('joi');
app.use(express.json());
const port = 6000;
const courses =[
{ id:1,
name:'courses 1'},
{ id:2, name:'courses 2'},
{ id:1, name:'courses 3'},
];
app.get('/',(req,res)=>{
res.send("hellow request for this site has been successfully done");
});
app.get('/api/courses',(req,res)=>{
res.send(courses);
});
app.get('/api/courses/:id',(req,res)=>{
let course = courses.find(c=> c.id === parseInt (req.params.id));
if (!course)res.status(404).send('<h1> 404 found</h1>')
res.send(course);
});
app.put('/api/courses/:id',(req,res)=>{
let course = courses.find(c=> c.id === parseInt (req.params.id));
if (!course)res.status(404).send('<h1> 404 found</h1>')
const {error} = validateCourse(req.body);
if(error){
res.status(400).send(error)
return;
}
course.name = req.body.name;
res.send(course);
});
app.post('/api/courses',(req,res)=>{
const {error} = validateCourse(req.body);
if(error){
res.status(400).send(error)
return;
}
const course ={
id: courses.length + 1,
name : req.body.name
};
courses.push(course);
res.send(course);
});
app.listen(port,()=>{
console.log(" kokab your server is runing " + port)
})
// validatecourse for repetation of course
validateCourse = (course) =>{
const schema = {
name: Joi.string().min(3).required()
};
return result = Joi.validate(course, schema);
}
// terminal error
C:\Users\DELL\Desktop\node> node app
events.js:174
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE: address already in use :::6000
at Server.setupListenHandle [as _listen2] (net.js:1279:14)
at listenInCluster (net.js:1327:12)
at Server.listen (net.js:1414:7)
at Function.listen (C:\Users\DELL\Desktop\node\node_modules\express\lib\application.js:618:24)
at Object.<anonymous> (C:\Users\DELL\Desktop\node\app.js:53:5)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
Emitted 'error' event at:
at emitErrorNT (net.js:1306:8)
at process._tickCallback (internal/process/next_tick.js:63:19)
at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
Use Below command to kill the process
lsof -i:<port_number>
kill -9 <PID>
You can do it using the following ways
sudo kill $(lsof -t -i:PORT)
OR
sudo fuser -k -n tcp PORT
OR
fuser -k PORT/tcp
Please replace the PORT with the needed port.

TypeError: connection.model is not a function in mongoose-auto-increment

I tried to connect mongodb. But I couldn't it. I thought [autoIncrement.initialize] is problem, but I couldn't solve the problem. This is my code.
const mongoose = require('mongoose');
const autoIncrement = require('mongoose-auto-increment');
require('dotenv').config();
mongoose.Promise = global.Promise;
const connect = mongoose.connect(process.env.MONGODB_URI);
autoIncrement.initialize(connect);
Here is error traceback:
/Users/loo/Projects/example-app/node_modules/mongoose-auto-increment/index.js:27
throw ex;
^
TypeError: connection.model is not a function
at Object.exports.initialize (/Users/loo/Projects/example-app/node_modules/mongoose-auto-increment/index.js:10:34)
at Object.<anonymous> (/Users/loo/Projects/example-app/app.js:8:15)
at Module._compile (internal/modules/cjs/loader.js:702:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
at Module.load (internal/modules/cjs/loader.js:612:32)
at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
at Function.Module._load (internal/modules/cjs/loader.js:543:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:744:10)
at startup (internal/bootstrap/node.js:238:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:572:3)
As You read example in this link
You would see this:
var connection = mongoose.createConnection("mongodb://localhost/myDatabase");
autoIncrement.initialize(connection);
In fact .connect and .createConnection are different things.
Due to documentation here which says:
Mongoose creates a default connection when you call
mongoose.connect().
You can access the default connection using
mongoose.connection.
that means mongoose.connect does not return connection and You can get that connection using mongoose.connection.
Solution:
mongoose.connect(process.env.MONGODB_URI, {useNewUrlParser: true})
.then(() => {
console.log('Connected to DB');
})
.catch(error => {
console.error('Connection to DB Failed');
console.error(error.message);
process.exit(-1);
});
autoIncrement.initialize(mongoose.connection);
or You can create a connection as here:
const connection = mongoose.createConnection(process.env.MONGODB_URI);
autoIncrement.initialize(connection);

Hapi js - makemehapi Issue

Hi New Node and I am practising tutorial "makemehapi" In the third assignment I have receiving below error. Any one can point where I am doing wrong?
Regards,
Surya
------------ Code ---------------------
var Path = require('path');
var Hapi = require('hapi');
var Inert = require('inert');
var server = new Hapi.Server();
server.connection({
host: 'localhost',
port: Number(process.argv[2]|| 8080)
});
server.register(require(Inert),function(err){
if(err) throw err;
} )
server.route({
method:'GET',
path:"/index.html",
handler: {
file: "index.html"
}
})
server.start(function () {
console.log('Server running at:', server.info.uri);
});
---------------------- error--------------------------
assert.js:86
throw new assert.AssertionError({
^
AssertionError: path must be a string
at Module.require (module.js:364:3)
at require (module.js:384:17)`enter code here`
at Object.<anonymous> (/home/surya/Desktop/nodeschool/Hapi Practice/test/Lesson3.js:13:17)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
✗ Error connecting to http://localhost:18384: ECONNREFUSED
events.js:85
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED
at exports._errnoException (util.js:746:11)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1010:19)
You are requiring in Inert twice. Remove the require around the Inert variable in the following line:
server.register(require(Inert),function(err){
if(err) throw err;
});
To:
server.register(Inert,function(err){
if(err) throw err;
});

Resources