I am trying to connect my Node.js (Express) with my MongoDB atlas by following the official tutorial on their website.
Here is my conn.js code below:
const { MongoClient } = require("mongodb");
const Db = process.env.ATLAS_URI;
let _db;
module.exports = {
connectToServer: function (callback) {
MongoClient.connect(
Db,
{ useNewUrlParser: true, useUnifiedTopology: true },
(err, db) => {
console.log('THIS LOG IS NOT DISPLAYED')
if (db) {
_db = db.db("employees");
console.log("Successfully connected to MongoDB");
}
return callback(err);
}
);
},
getDb: function () {
return _db;
},
};
Here is server.js where I am calling connectToServer() function from conn.js
const express = require("express");
const app = express();
const cors = require("cors");
require("dotenv").config({ path: "./config.env" });
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
app.use(require("./routes/record"));
const dbo = require("./db/conn");
app.listen(port, () => {
// HERE IS WHERE I CALL THE FUNCTION
dbo.connectToServer(err => {
if (err) console.error(err);
});
console.log(`Server is running on port: ${port}`);
});
Note, that I am getting the "Server is running on port: 5000" message, but I am not getting the "Successfully connected to MongoDB" message and I am not getting any errors, too.
P.S. I made my MongoDB network access 0.0.0.0 so that any IP address can access it. And also if I provide the wrong username and password for my ATLAS_URI, I am getting an authentication error.
Connect returns promise you can use like below.
let _db;
const client = new MongoClient(Db, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
module.exports = {
connectToServer: async (callback) => {
await client.connect();
console.log("Connected successfully to server");
_db = client.db(dbName);
console.log("Successfully connected to MongoDB");
},
getDb: function () {
return _db;
},
};
Note: You can change the order If you want, First connect to DB then start the server. It's completely optional depending on the use case.
(async () => {
try {
await dbo.connectToServer();
app.listen(port, async () => {
// HERE IS WHERE I CALL THE FUNCTION
console.log(`Server is running on port: ${port}`);
});
} catch (error) {
console.log(error);
}
})();
Callback Support has been removed from v5 hence the console.log statements in callback function are not getting printed. To make it work you can use promises/async-await.
Due to same reason an error is thrown when authentication is wrong as connect function is running but failing in this case.
Change log for the same. => "Node.js driver v5 drops support for callbacks in favor of a Promise-only API."
Related
I understand that we need to use asynch and await while connecting db since models are loading before db connection happening so i have used and call the function in server.js Please look into my code and help me.
Connection.js
const mongoose = require('mongoose');
mongoose.set('strictQuery', true);
module.exports = async () => {
console.log(process.env.DB_URL);
await mongoose.connect(process.env.DB_URL, {
useNewUrlParser: true,
//useUnifiedTopology: true
}).then(()=>{
console.log("Database Connected");
}).catch (error => {
console.log("Database connectivity Error", error);
});
}
Server.js
const express = require('express');
const dotEnv = require('dotenv');
const { urlencoded } = require('express');
const cors = require('cors');
const dbConnection = require('./database/connection');
dotEnv.config({path:'./.env'});
const app = express();
// Database connection
// cors
app.use(cors());
app.use(express.json());
dbConnection();
app.use('/api/v1/domain', require('./routes/domainRoutes') );
app.get('/', (req, res, next)=>{
res.send("Hello From node aPI server");
});
// request payload middleware
app.use(express.json);
app.use(urlencoded({extended:true}))
const PORT = process.env.PORT || 3000;
app.listen(PORT, ()=>{
console.log(`Server Listen on port ${PORT}`);
});
// error handling middle ware
app.use(function(err, req, res,next){
console.error(err.stack)
res.status(500).send({
status: 500,
message:err.message,
body:{}
})
});
DomainService.js
const Domain = require('../database/models/DomainModel');
module.exports.createDomain = async (serviceData) => {
try {
let domain = new Domain({...serviceData})
return await domain.save();
} catch (error) {
console.log("Soemthing wrong: Service : Create Domain ", error);
throw new Error(error);
}
}
you can find full code here
https://github.com/vlpreddy/node-express-rest-api
I am trying to develop rest api's using nodeJs, tried to connect with mongoddb using mongoose. I am getting this timeout error since 2 days, i tried most of the solutions in the internet including using await and async.
So can someone please look into my code and help me.
Since I was stupid enough, I haven't installed mongodb in my system, so it was not connecting obviously. But I felt like it suppose to throw an error like
dude there is no mongodb in your system, how the heck do you think you
can create database and store the collections.
Any how people who are coming here with same error but a different reason can utilise following code and connect database using async and await functions as new version can load models with out even caring whether database is connected or not.
**database/connection.js**
const mongoose = require('mongoose');
mongoose.set('strictQuery', true);
module.exports = async () => {
//console.log(DB_URL);
await mongoose.connect(process.env.DB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(()=>{
console.log("Database Connected");
}).catch (error => {
console.log("Database connectivity Error", error);
});
}
you can import in any page and call the variable as a function
since it returns a promise function which is written below.
const dbConnection = require('./database/connection');
dbConnection();
I have been trying to connect to mongodb via my node app on a shared hosting cpanel but it only responds with error code 503 and logs "db.collection undefined" to the console, which means the connection was not successful.
This is the database connection in db.js:
const { MongoClient } = require('mongodb');
require('dotenv').config();
let dbConnection;
module.exports = {
connectToDb: (cb) => {
MongoClient.connect(`mongodb+srv://Achifa:${process.env.PASSWORD}#cluster0.exp9r.mongodb.net/?retryWrites=true&w=majority`)
.then((client) => {
dbConnection = client.db('newsDb')
return cb()
})
.catch(err => {
console.log(err)
return cb(err)
})
},
getDb: () => dbConnection
}
This is the app connection in app.js:
const {connectToDb, getDb} = require('./db');
let db;
var port = process.env.PORT || 50500;
connectToDb((err) => {
if(!err){
var server = app.listen(port, () => console.log("connected"));
db = getDb();
}
})
I'm a beginner and try to create a rest API following this tutorial. I expected to see Server is running on port: ${PORT}, but it seems like my code can't reach it. I got no error on my terminal and it looks like this
Here are my code:
server.js
require('dotenv').config({ path: './config.env' });
const express = require('express');
const cors = require('cors');
const dbo = require('./db/conn');
const PORT = process.env.PORT || 5000;
const app = express();
app.use(cors());
app.use(express.json());
app.use(require('./api/api'));
// Global error handling
app.use(function (err, _req, res) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
// perform a database connection when the server starts
dbo.connectToServer(function (err) {
if (err) {
console.error(err);
process.exit();
}
// start the Express server
app.listen(PORT, () => {
console.log(`Server is running on port: ${PORT}`);
});
});
conn.js
const MongoClient = require('mongodb').MongoClient
const dotenv = require("dotenv")
dotenv.config()
const connectionString = process.env.MONGOURI
let db;
module.exports = {
connectToServer : function(callback) {
MongoClient.connect(connectionString, {
useUnifiedTopology: true
}, (err, client) => {
if (err) return console.error(err)
db = client.db('db-name');
console.log('Connected to Database');
return callback
});
},
getDb: function () {
return db;
}
}
api.js
const express = require("express");
const gameRoutes = express.Router();
const dbo = require('../db/conn');
gameRoutes.route("/game").get(async function (_req, res) {
const dbConnect = dbo.getDb();
dbConnect
.collection("game")
.find({}).limit(50)
.toArray(function(err, result) {
if (err) {
res.status(400).send("Error fetching listings!");
} else {
res.json(result);
}
})
})
module.exports = gameRoutes;
Can you please tell me what's wrong with my code? I really can't find why the server is not running. Thanks in advance! I'll be very grateful for your help!
In your connectToServer method you just returning the callback. But you actually need to call it as well.
So change this
return callback
to this
return callback(null);
If you want to pass the possible error from MongoClient to the callback as well, then change your connectToServer method to this :
connectToServer : function(callback) {
MongoClient.connect(connectionString, {
useUnifiedTopology: true
}, (err, client) => {
if (err) { return callback(err); }
db = client.db('db-name');
console.log('Connected to Database');
return callback(null) // no error, so pass "null"
});
}
I have a tiny express server that I want to use to get some data from a collection in my database:
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const app = express();
const PORT = 3000;
const MONGO_URI = 'mongodb://127.0.0.1:27017/test';
async function myReport(schoolId) {
const client = new MongoClient(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect()
console.log("Hello!"); // This is never ran unless I remove "await" from the above line :S
const db = client.db();
const result = db.collection('states').find({}).map((a, b, c) => {
console.log("This never runs", a, b, c);
return "asdf";
});
return result;
} catch (err) {
console.log("ERROR", err);
}
client.close();
};
// Hoisting server
app.get('/api/reports/states/:id', async function (req, res, next) {
const report = myReport(req.params.id)
res.json(report); // {}
});
app.listen(PORT, (err) => {
console.log(`reporting listening in`, PORT);
});
I really don't know what I'm doing wrong here. Tried using .each, toArray and I'm not able to get the actual results as a list.
I've been following these docs: https://mongodb.github.io/node-mongodb-native/3.6/api/Cursor.html
Any idea what I'm doing wrong?
As per your saying:
await client.connect()
console.log("Hello!"); // This is never ran unless I remove "await" from the above line :S
I think connection is not establishing. I tried your code with a little bit modification. I created a cluster on Atlas Mongodb and used its URI as a connection string.
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const app = express();
const PORT = 3000;
const MONGO_URI = 'mongodb+srv://<username>:<password>#cluster0-oqotc.mongodb.net/<dbname>?retryWrites=true&w=majority';
const getListings = async () => {
const client = new MongoClient(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect()
console.log("Hello!"); // This will print now :-)
const listings = await client.db("sample_airbnb").collection("listingsAndReviews").findOne({});
return listings;
} catch (err) {
console.log("ERROR", err);
}
client.close();
};
// Hoisting server
app.get('/api/get-listings', async function (req, res, next) {
const report = await getListings()
res.json(report);
});
app.listen(PORT, (err) => {
console.log(`reporting listening in`, PORT);
});
You need to change username, password and dbname with your ones.
Note: While using Atlas Mongodb Cluster, if you are getting connection error, you need to whitelist your ip as well.
Hope it will help you. Thanks
You defined myReport as an asynchronous function which returns a promise. Add toArray() back into your code and then get your report like this
app.get('/api/reports/states/:id', async function (req, res, next) {
myReport(req.params.id).then(report => {
res.json(report);
});
});
Because its the call to res.json is also in an asynchronous function I think you can also do
app.get('/api/reports/states/:id', async function (req, res, next) {
const report = await myReport(req.params.id);
res.json(report);
});
So my issue is that the program obviously isn't working, but it also isn't crashing. It's like it never executes the try or catch.
const express = require("express"),
app = express(),
sql = require("mssql"),
port = 5000 || process.env.PORT,
bodyParser = require("body-parser"),
routerBoi = express.Router();
const sqlConfig = {
user: "sa",
password: "#Strongman105",
server: "DESKTOP-RVS5F2QHSTESTSERVER",
database: "master"
};
async () => {
try {
// make sure that any items are correctly URL encoded in the connection string
await sql.connect(sqlConfig);
const result = await sql.query(`select * from Users`);
console.log(result);
} catch (err) {
console.log(err);
}
};
// console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
The entirety of my output is "Listening on port 5000".
What am I doing wrong here?
(async function() {
try {
await sql.connect(sqlConfig);
const result = await sql.query(`select * from Users`);
console.log(result);
} catch (err) {
console.log(err);
}
})();
Just wrap your async function with round braces and make it self execution function. you can refer this in the official docs. https://www.npmjs.com/package/mssql#asyncawait