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();
Related
throw new MongooseError('The uri parameter to openUri() must be
a ' +
^
MongooseError: The uri parameter to openUri() must be a string,
got "undefined". Make sur
first parameter to mongoose.connect() or mongoose.createConnection() is a string.
at NativeConnection.Connection.openUri (C:\Users\niko\Desktop\opaa\node_modules\mongoose\nnection.js:694:11)
at _mongoose._promiseOrCallback.cb (C:\Users\niko\Desktop\opaa\node_modules\mongoose\lib\js:351:10)
at promiseOrCallback (C:\Users\niko\Desktop\opaa\node_modules\mongoose\lib\helpers\promislback.js:10:12)
at Mongoose._promiseOrCallback (C:\Users\niko\Desktop\opaa\node_modules\mongoose\lib\inde at
Mongoose.connect
(C:\Users\niko\Desktop\opaa\node_modules\mongoose\lib\index.js:350:20)
at Object. (C:\Users\niko\Desktop\opaa\app.js:9:10)
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)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
const { response } = require('express');
const express = require('express');
const path = require('path');
const dotenv = require('dotenv')
const mongoose = require('mongoose');
dotenv.config();
mongoose.connect( process.env.DB_CONNECT, { useNewUrlParser: true }, () =>{
console.log("connected to db");
});
const route = require('./routers/routers');
const { connect } = require('./routers/routers');
const app = express();
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.set("views", "views")
app.set("view engine", "hbs")
app.use(express.static('public'));
app.use('/user', route);
app.listen(3000, () => console.log("Server Is Runing on localhost:3000"));
You may try to be sure you've passed the DB_CONNECT.
you may try DB_CONNECT=YOUR_DB_URI node index.js
also, you may check with console.log(process.env.DB_CONNECT) at the beginning of your script.
The error message tells that the mongoose.connect received URL is undefined. I suggest you instead process.env.DB_CONNECT try passing an URL to the DB for testing purpose see if that works.
The issue is with the process.env.DB_CONNECT is not setting up correctly, you might need to check dotenv configuration.
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();
});
};
I got this error in my application that is previously working
const usersCollection = require('../db').db().collection("users")
^
TypeError: require(...).db is not a function
at Object.<anonymous> (/Users/user/Desktop/sites/app/models/User.js:2:42)
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> (/Users/user/Desktop/sites/app/controllers/userController.js:1:14)
db.js
const dotenv = require('dotenv')
dotenv.config()
const mongodb = require('mongodb')
mongodb.connect(process.env.CONNECTIONSTRING, {useNewUrlParser: true, useUnifiedTopology:
true}, function(err, client) {
module.exports = client
const app = require('./app')
app.listen(process.env.PORT)
})
.env file
CONNECTIONSTRING=mongodb+srv://user:password#sandbox-gk8wp.mongodb.net/db?
retryWrites=true&w=majority
PORT=3000
I have updated also my mongodb npm package from 3.3.3 to 3.4.1 but still the same error. What seems to be the problem?
You are trying to export something in the callback which may or may not be available when you import it as it is asynchronous method. Better way will be to create db.js like
const dotenv = require('dotenv')
dotenv.config()
const mongodb = require('mongodb')
function getMongoClient() {
return mongodb.connect(process.env.CONNECTIONSTRING, {useNewUrlParser: true, useUnifiedTopology: true});
}
module.exports = getMongoClient;
And when you want to use it
const getMongoClient = require('../db');
getMongoClient()
.then(client => client.db().collection("users"));
Hope this helps. You could also use async/await.
I am following a tutorial on creating a Fullstack project Using MongoDB as my database. The tutorial is a bit outdated as it seems MongoDB has updated their process renaming the apps to clusters from what I can see. I tried connecting MongoDB to my server and received URL malformed, cannot be parsed as an error.
EDIT: I removed the images of the code
My server file:
const express = require("express");
const mongoose = require("mongoose");
require("dotenv").config({ path: "variables.env" });
mongoose
.connect(process.env.MONGO_URI)
.then(() => console.log("DB connected"))
.catch(err => console.error(err));
const app = express();
const PORT = process.env.PORT || 4444;
app.listen(PORT, () => {
console.log(`Server listening on PORT ${PORT}`);
});
My variable.env file:
MONGO_URI=mongodb+srv://Ernest:<password>#cluster0-ltxeh.mongodb.net/test?retryWrites=true&w=majority
Error Message:
Error: URL malformed, cannot be parsed
at module.exports (/Users/eboolo/Desktop/react-recipes/node_modules/mongodb/lib/url_parser.js:17:21)
at connect (/Users/eboolo/Desktop/react-recipes/node_modules/mongodb/lib/mongo_client.js:880:3)
at connectOp (/Users/eboolo/Desktop/react-recipes/node_modules/mongodb/lib/mongo_client.js:269:3)
at executeOperation (/Users/eboolo/Desktop/react-recipes/node_modules/mongodb/lib/utils.js:420:24)
at MongoClient.connect (/Users/eboolo/Desktop/react-recipes/node_modules/mongodb/lib/mongo_client.js:260:10)
at /Users/eboolo/Desktop/react-recipes/node_modules/mongoose/lib/connection.js:427:12
at new Promise (<anonymous>)
at NativeConnection.Connection.openUri (/Users/eboolo/Desktop/react-recipes/node_modules/mongoose/lib/connection.js:424:19)
at Mongoose.connect (/Users/eboolo/Desktop/react-recipes/node_modules/mongoose/lib/index.js:208:15)
at Object.<anonymous> (/Users/eboolo/Desktop/react-recipes/server.js:6:5)
at Module._compile (internal/modules/cjs/loader.js:774:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:785:10)
at Module.load (internal/modules/cjs/loader.js:641:32)
at Function.Module._load (internal/modules/cjs/loader.js:556:12)
at Function.Module.runMain (internal/modules/cjs/loader.js:837:10)
at internal/main/run_main_module.js:17:11
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);