Hi I am trying to connect MongoDB and I got an error. I worked on connecting DB by "connect with the MongoDB shell", but this time I want to connect with the "connect your application" option.
When I hit mongosh in the embedded terminal in my mac, below was returned.
Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.2.2
Using MongoDB: 5.0.6
Using Mongosh: 1.2.2
...
...
...
test>
Because I am new to MongoDB, I don't even know if it's correctly working or not. Also, I wanna connect by coding. That's why I am asking here. Below are some parts of my code in an app I have been working on.
Thanks for your time for dedication here. So appreciate it.
// this is db.js file in a config folder.
const mongoose = require('mongoose')
// It must be a promise function to connect db
const connectDB = async () => {
try {
console.log(`try`)
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
dbName: 'expense2'
});
console.log(`MongoDB Connected: ${conn.connection.host}`.syan.underline.bold)
} catch (error) {
console.log(`Error: ${error.message}`.red)
process.exit(1);
}
}
module.exports = connectDB;
/*
Here is the error happened
Error: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/
[nodemon] app crashed - waiting for file changes before starting...
*/
config.env in the config folder as well.
NODE_ENV = development;
PORT=5000
MONGO_URI=mongodb+srv://mongo:mongo#cluster0.8tjjn.mongodb.net/expense2?retryWrites=true&w=majority
// server.js file
const express = require('express');
const dotenv = require('dotenv');
const colors = require('colors');
const morgan = require('colors');
const connectDB = require('./config/db')
dotenv.config({ path: "./config/config.env" })
connectDB();
const app = express();
const transactionsRouter = require('./routes/transactions')
app.use('/transactions', transactionsRouter)
const PORT = process.env.PORT || 5000;
app.listen(PORT, console.log(`server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold));
Related
I am getting the below error when I am trying to establish a database connection in my node js application using sequelize
C:\Users\user123\Desktop\project\node_modules\tedious\lib\token\token-stream-parser.js:24
this.parser = _stream.Readable.from(_streamParser.default.parseTokens(message, this.debug, this.options));
^
TypeError: _stream.Readable.from is not a function
I am in initial stage of creating an application. Where I have just tried to create a database connection, for which I have created three files
index.js
var dotenv = require("dotenv").config().parsed;
var customEnv = require("custom-env");
customEnv.env("development").env();
var express = require("express");
const helmet = require("helmet");
var cookieParser = require("cookie-parser");
const app = express();
app.use(helmet());
app.use(cookieParser());
require("./db.js");
httpserver = require("http").createServer(app);
httpserver.timeout = 0;
httpserver.listen(3457, async () => {
connectedEmitter.on("connectedDbs", () => {
console.log(` ----- SERVER LISTENING ON PORT `);
});
});
db.js
const Sequelize = require('sequelize');
const eventEmitter = require('events');
global.connectedEmitter = new eventEmitter()
global.sequelize = new Sequelize(process.env.DB_NAME, process.env.DB_USER, process.env.DB_PASS, {
host: process.env.DB_HOST,
port: 1433,
dialect: process.env.DB_DIALECT,
ssl: false,
dialectOptions: {
ssl:false
},
logging:false,
pool: {
max: 20,
min: 0,
idle: 30000
}
});
sequelize.authenticate().then(() => {
console.log(`${process.env.DB_NAME} - Connection has been established successfully.`);
global.connectedEmitter.emit('connectedDbs')
}).catch((err) => {
console.error(' - Unable to connect to the database:', err);
});
.env (I am giving dummy credentials as I cannot provide original credentials)
# ################################## Database Credentials ##############################################
DB_NAME=mydb
DB_USER=username
DB_PASS=password
DB_HOST=hostname
DB_DIALECT=mssql
Can anyone please tell me why am I getting the error mentioned. Where have I made the mistake in setting the database connection. Please help.
I also faced this issue. Turns out tedious had issues with node versions below 12, and my production app service was running on node 10.
GitHub link that mentions this
I have looked around for a solution, but I can't seem to figure this out. What I'm trying to do is make POST/GET requests to a PostgreSQL database from an Express server.
main.js:
var app = require('../app');
var debug = require('debug')('server:server');
var http = require('http');
var port = normalizePort(process.env.PORT || '8000');
app.set('port', port);
var server = http.createServer(app);
server.listen(port, () => {
console.log(`Server is running on localhost:${port}`);
});
server.on('error', onError);
server.on('listening', onListening);
app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var helmet = require('helmet');
var indexRouter = require('./routes');
var app = express();
app.use(cors());
app.use(helmet());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
module.exports = app;
routes.js (Handling the api requests)
router.post('/api/post/userprofiletodb', async (req, res, next) => {
console.log(req);
const values = [req.body.profile.nickname, req.body.profile.email, req.body.profile.email_verified];
// ON CONFLICT DO NOTHING - prevents the user profile from being stored in db twice
await pool.query(`INSERT INTO users(username, email, email_verified, date_created)
VALUES($1, $2, $3, NOW() )
ON CONFLICT DO NOTHING`, values,
(q_err, q_res) => {
if (q_err) return next(q_err);
console.log(q_res);
res.json(q_res.rows);
})
})
router.get('/api/get/userprofilefromdb', async (req, res, next) => {
console.log(req);
const email = String(req.query.email);
await pool.query(`SELECT * FROM users WHERE email=$1`, [email],
(q_err, q_res) => {
if (q_err) return next(q_err);
res.json(q_res.rows);
})
})
db.js:
const { Pool } = require('pg');
const pool = new Pool({
user: 'postgres',
host: 'localhost',
database: 'mydb',
password: 'mypassword',
post: 5432
});
module.exports = pool;
React code (Action Creators for Redux):
export const setDbProfile = (profile) => async(dispatch) => {
const response = await axios.post('http://localhost:8000/api/post/userprofiletodb', profile);
dispatch({ type: SET_DB_PROFILE, payload: response.data });
console.log(response);
history.replace('/');
}
export const getDbProfile = (profile) => async(dispatch) => {
const data = profile;
console.log('getDbProfile', profile);
const response = await axios.get('http://localhost:8000/api/get/userprofilefromdb',
{
params: {
email: data.profile.email
}
}
)
dispatch({ type: GET_DB_PROFILE, payload: response.data });
history.replace('/');
Here is my thought process:
- I have my Express server set up on http://localhost:8000 and my React application is running on http://localhost:3000 (I have already included a proxy in the package.json file).
- When the action creator is called, it first does a post request to http://localhost:8000 where my Express server is on.
- The Express server sees this and makes a request to the PostgreSQL database stored on localhost: 5432.
However, I'm getting this error....
POST /api/post/userprofiletodb 500 182.558 ms - 250
Error: connect ECONNREFUSED 127.0.0.1:5432
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1117:14)
GET /api/get/userprofilefromdb?email=dasfdfasfdf#gmail.com 500 52.541 ms - 250
Error: connect ECONNREFUSED 127.0.0.1:5432
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1117:14)
I think there may be an issue with my PostgreSQL database. How I set that up is by opening up SQL Shell (psql) and did the following:
- CREATE DATABASE mydb;
- \c mydb
- CREATE TABLE users(...);
- CREATE TABLE posts(...);
- CREATE TABLE comments(...);
Not too sure how I could solve this... Any guidance would be greatly appreciated! Cheers.
UPDATE:
When I run the command
netstat -na
I do not see, 127.0.0.1.5432 listed at all... Does this mean my database is just not setup properly?
Running SQL Shell (psql)
x-MacBook-Air:~ x$ /Library/PostgreSQL/12/scripts/runpsql.sh; exit
Server [localhost]:
Database [postgres]:
Port [5000]: 5432
Username [postgres]:
psql: error: could not connect to server: could not connect to server: Connection refused
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
Press <return> to continue...
I'm trying to connect to my MongoDB Atlas database, but it's not working, and I can't seem to figure out why.
I've made sure I don't use illegal characters in my username and password, I've tried different connection strings. I've tried turning off my firewall.
server.js
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const app = express();
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
const db = require("./keys").mongoURI;
mongoose.connect( db, { useNewUrlParser: true } )
.then(() => console.log("MongoDB successfully connected"))
.catch(err => console.log(err));
const port = process.env.PORT || 5000; // process.env.port is Heroku's port if you choose to deploy the app there
app.listen(port, () => console.log(`Server up and running on port ${port} !`));
keys.js
module.exports = {
mongoURI: "mongodb+srv://username:password#mernauth-lksvn.mongodb.net/test?retryWrites=true&w=majority"
};
I replaced the username and password in the connection string with the real username and password.
EDIT: SOLUTION
Even though I used both my IP address and the default IP address MongoDB Atlas suggested for me, neither worked. I guess I didn't have a valid IP address, so once I opened the database to all IP addresses, it worked!
I have the most basic bones of a new app.js set up with sequelize and express in node. Whenever I run the project I get:
{ Error: SQLITE_CANTOPEN: unable to open database file errno: 14, code: 'SQLITE_CANTOPEN' }
I've searched around for solutions, but I'm not using other technologies like electron that seem to cause issues, according to the other posts I found. I did also try the suggestion of moving my database.sqlite3 from the root directory into its own folder, but that did not help.
My app.js looks like a boilerplate still. I am really not doing much, just trying to test a connection after creating models and migrating using the sequelize-cli.
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
//Database Connection
const db = require('./config/database');
const Sequelize = require("sequelize");
const sequelize = new Sequelize({
dialect: "sqlite",
storage: "path/to/database.sqlite"
});
//Test the DB Connection
sequelize.authenticate()
.then(() => console.log('Database Connected'))
.catch(err => console.log('Error: ', err))
//Server
const app = express()
app.get('/', (req, res) => res.send('HELLO WORLD'))
const PORT = process.env.PORT || 5000;
app.listen(PORT, console.log(`Server started on ${PORT}`));
My config.json is as follows, and I did double check the path.
{
"development": {
"dialect": "sqlite",
"storage": "./db/database.sqlite3"
},
"test": {
"dialect": "sqlite",
"storage": ":memory"
},
"production": {
"dialect": "sqlite",
"storage": "./db/database.sqlite3"
}
}
It looks like you still have boilerplate code in your file. Specifically, look at these lines:
const sequelize = new Sequelize({
dialect: "sqlite",
storage: "path/to/database.sqlite"
});
It doesn't look like you're using the configuration file; instead, you're trying to open a database file at path/to/database.sqlite3.
Try this instead:
const sequelize = new Sequelize(db[process.env.NODE_ENV]);
(I'm assuming you want to load the database config corresponding to the current environment).
My connection code is entered below. I'm trying to connect to the MongoDB atlas free shared cluster and I keep getting an error saying cannot connect to the server in the first time.
const express = require("express");
const app = express();
const morgan = require("morgan");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
mongoose.Promise = require('bluebird');
const productRoutes = require("./api/routes/products");
const orderRoutes = require("./api/routes/orders");
mongoose.connect(
"mongodb://username:password6#cluster0-shard-00-00-3xdjv.mongodb.net:27017,cluster0-shard-00-01-3xdjv.mongodb.net:27017,cluster0-shard-00-02-3xdjv.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin",
{
useMongoClient: true
}
) .then(() => { // if all is ok we will be here
return server.start();
})
.catch(err => { // we will not be here...
console.error('App starting error:', err.stack);
process.exit(1);
});
Can someone explain why I keep getting this error:
App starting error:
MongoError: failed to connect to server [cluster0-shard-00-00-3xdjv.mongodb.net:27017] on first connect
[MongoError: getaddrinfo EAI_AGAIN
cluster0-shard-00-00-3xdjv.mongodb.net:27017].....
I had the same problem before I realized that I had set up a network access rule allowing only connections from a certain IP. After deleting that restriction and adding a new rule for allowing all connections from anywhere, the problem was gone
My datasource config is as follows:
"mongodb-atlas": {
"url": "mongodb+srv://dbuser:PaSsWOrd#cluster0-oxxxb.gcp.mongodb.net/test?retryWrites=true&w=majority&authSource=admin",
"name": "mongodb-atlas",
"connector": "mongodb",
"database": "admin"
}