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();
Related
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."
I'm trying to make request to a postgreSQL DB being accessed by a Node + Express server that I've deployed on Heroku. This is the error im getting when running 'heroku logs': Error: connect ECONNREFUSED 127.0.0.1:5432, along with a couple other errors. I'm using axios on the frontend to make request.
Here is my server.js file:
// express
const express = require('express');
// environment variables
require('dotenv').config();
// data base connector
const db = require('./db');
// cors
const cors = require('cors');
// express instance
const app = express();
// use cors
app.use(cors());
// attach data to req.body
app.use(express.json());
// get all articles
app.get('/api/v1/articles', async (req, res, next) => {
try {
// query database
const results = await db.query('SELECT * FROM articles;');
// send results
res.status(200).json({
results: results.rows
});
// handle error
} catch (err) {
next(err);
}
});
// get individual article
app.get('/api/v1/articles/:id', async (req, res, next) => {
try {
// query database
const article = await db.query(`SELECT * FROM articles WHERE id = $1;`, [req.params.id]);
// send back data
res.status(200).json({
article: article
});
// handle error
} catch (err) {
next(err);
}
});
// get article's comments
app.get('/api/v1/articles/:id/comments', async (req, res, next) => {
try {
// query database
const comments = await db.query(`SELECT * FROM comments WHERE article_id = $1;`, [req.params.id]);
// send back data
res.status(200).json({
comments: comments
});
// handle error
} catch (err) {
next(err);
}
});
// add comment
app.post('/api/v1/articles/:id/comments', async (req, res, next) => {
try {
// post comment in database
const comment = await db.query(`INSERT INTO comments (article_id, author, text)
VALUES ($1, $2, $3) returning *;`, [req.body.article_id, req.body.author, req.body.text]);
// send comment back
res.status(201).json({
comment
});
// handle error
} catch (err) {
next(err);
}
})
// listen
const port = process.env.PORT || 3001;
app.listen(port, () => {
console.log(`Server now listening on PORT ${port}`);
});
I'm supposedly connected to my DB with the pg library, and the Pool gets the credentials from an .env file. I'm able to connect to the DB within pgAdmin and write queries, make tables etc.
Any help greatly appreciated
Check your database connection configuration. The error shows that it tries to connect to PostgreSQL on 127.0.0.1 which is LOOPBACK ip address. This means that is trying to access the server on your machine. You need to configure the connection by specifying the correct address for the server where PostgreSQL is running
I am trying to create a chat app which, uses a real-time database with MongoDB and Websocket.
This is my first React, MongoDB, and Websocket Project, so please excuse possible trivialities. :D
I am currently working on creating a new user, refreshing the database, and finally displaying the created user in every user's frontend in real-time.
Creating and saving a new user works fine and also logging the new user's data in real-time after the database changed (via socket.io) is working as well. Now, I would like to access the information that the database changed in the frontend of my app, so I can refresh the unordered list of users. Now there is the problem I'd like to solve: I try to connect the frontend with my backend by using this code:
//...
import socketIOClient from "socket.io-client";
const ENDPOINT = "localhost:5000";
const MainContentArea = () => {
useEffect(()=>{
const socket = socketIOClient(ENDPOINT);
socket.on("changes", data => {
console.log(data);
})
});
//...
The following is my backend code:
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const index = require('./routes/index');
const port = process.env.PORT || 5000;
const app = express();
app.use(index);
const server = app.listen(port, () => {
console.log(`Server ist running on port: ${port}`);
})
const io = socketIo(server).listen(server);
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config({
path: './.env'
});
const Users = require('./models/user.model');
app.use(cors());
app.use(express.json());
const usersRouter = require('./routes/users');
app.use('/users', usersRouter);
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
},
function(err){
if(err){
console.log("server.js err line 44");
throw err;
}
io.on('connection', (socket) => {
console.log('user connected');
socket.on('disconnect', (socket) => {
console.log('user disconnected');
})
})
Users.watch().on('change', (change) => {
console.log('socket says: something changed in db');
console.log('change: ', change.fullDocument);
io.to(change.fullDocument).emit('changes',change.fullDocument)
})
}
);
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
I keep getting the Error message:
WebSocket connection to 'ws://localhost:5000/socket.io/? EIO=3&transport=websocket&sid=33wU6D8PnqclT3iZAAAB' failed: Error during WebSocket handshake: Unexpected response code: 400
I am using Chrome and I am working on MacOS.
I am very thankful for any suggestions that might help solve my problem.
I hope, how I posted my question is helpful for anybody who is willing to help me with this. If not, feel free to give me suggestions on what to do better next time! This is my first post here.
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);
});
I am writing an app, when I start the server, its working nicely, its connecting to database. But when I start http://localhost:5000 from the browser, it does not respond for a minuite then the browser shows a message:
localhost didn’t send any data.
ERR_EMPTY_RESPONSE
Here is my app.js:
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');
app.use(cookieParser);
app.use(express.json());
//const userRouter = require('./routes/user');
//app.use('/user', userRouter);
const startApp = async () => {
try {
await mongoose.connect('mongodb+srv://username:pass#cluster0-dcytp.mongodb.net/test?retryWrites=true&w=majority',
{ useUnifiedTopology: true,useNewUrlParser: true });
console.log(`successfully connected to database`);
const port = process.env.PORT || 5000
app.listen(port, () => {
console.log(`server runnin at ${port}`);
});
} catch (error) {
console.log(error.message)
}
}
startApp();
app.get('/', (req, res) => {
console.log("I am in the root");
res.send("hello World");
})
Why server is not responding from the browser?
try
app.use(cookieParser())
instead of
app.use(cookieParser)
Reference
I had the same problem db is connected but not able to send data. it looks weird but it works for me.
Add a new database user with new password, use the new userName and passw to connect your mongoodb
this is the exact like to add new database user
here is my db connection may it helps you too
mongoose.connect(DATABASE_URL, { useNewUrlParser: true,useUnifiedTopology: true })
const db = mongoose.connection
db.on('error', (error) => console.error(error))
db.once('open', () => console.log('connected to database'))
app.use(express.json())