I'm trying to create a connection to MongoDB from a Node.JS application but I can't get the connection working. I just get errors saying:
TypeError: mongoose.createConnection is not a function
Same for just mongoose.connection also..
I just have a serivce class and I'm trying to create a connecting inside of it:
const mongoose = require('mongoose');
export class MongoDbService{
constructor(){
db = mongoose.createConnection(url)
.on('error', console.error.bind(console, 'connection error:'))
.once('open', function callback() {
console.log('db connection open');
});
console.log(db);
}
Surely this is possible ???
I'm trying to build a web application that talks to mongodb, nothing fancy at all.. Mongoose v5.1.6 is install also.
Related
I'm trying to establish a simple connection to my database with the mysql npm package. At first glance, everything works fine and I can get the information I need, however, if I leave the server running for some time I get the following error:
Error: read ECONNRESET
at TCP.onStreamRead
const express = require('express');
const app = express();`
const mysql = require('mysql');
const db = mysql.createConnection({
host: 'XXXX.mysql.database.azure.com',
user: 'XXXXX',
password: 'XXXXX',
database: 'XXXXX'
})
db.connect((err)=>{
if(err){
console.log(err.message);
} else {
console.log('Connected to the database');
}
})
As far as I understand the problem stems from the database connection being in idle mode. Do I need to configure the Azure server or is there something else I need to do?
Couple of things to try:
You can try creating connection pool instead of **createConnection**
mysql.createPool({});
Modify your package.json like below:
"dependencies": {
"mysql": "git://github.com/mysqljs/mysql#e3e123e9af7c0829a6c1417d911572a75b4a5f95"
},
It is described in detail here:
Bad handshake or ECONNRESET Azure Mysql Nodejs
https://social.msdn.microsoft.com/Forums/en-US/c8fedbcc-909d-41ce-8c72-0374f76fdf82/cannot-connect-from-nodejs?forum=AzureDatabaseforMySQL
Hope it helps.
Why when I separate the mongoose.connect invocation to a different file, the program would create new connections every request? It maxed out my mongo atlas connection usage
//I put the connect in a middleware
//middleware.js
const mongoose = require('mongoose')
function connect(req, res, next) {
mongoose.connect(db_url, {}, function (error) { //handle next })
}
module.exports = connect
//and called it in the app
app.use(mongoMiddleware)
The above would create tons of connection, the case is different when I invoke connect in the main app.js
//app.js
mongoose.connect(db_url, {}, function (error) {})
with the above code, the connection usage is 'stable', it doesn't fill out all the available connection.
Instead of using app.use()
(its not needed to use the connection as a middleware,instead make a connect function and export that)
then just require the mongoose connection file in app.js
const mongooseConnection=require("path to the connect function")
the connection code would be we executed when you run the node app.
I'm starting at Node.js and i'm trying to make a simple connection with Sequelize based on its documentation (http://docs.sequelizejs.com/manual/installation/getting-started.html#installation).
Here my db.js file :
const Sequelize = require('sequelize')
const db = new Sequelize('chat','root','root',{
host: 'localhost',
port: 3306,
dialect: 'mysql'
});
db
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
When executing this code, I have no success nor error message, just a message indicating 'String base operators deprecated' but nothing important i think.
I tried changing localhost to 127.0.0.1, remove port number and multiples thread but i'm stucked here...
Tested your code and all seemed to work fine, it connected successfully to the database instance I have running.
You might want to ensure mysql2 package is installed. Also check that the database chat has been created in MySQL workbench, and ensure the password is correct.
Yosemite Mongo user working through a MEAN book. I've been following the steps exactly, but the MongoDB isn't connecting as expected. I installed Mongo once before to mess around with importing data, but didn't get too far. Below is all the Mongo related code I have besides package.json:
In app.js I have require('./app_server/models/db'); and in that folder I have:
var mongoose = require( 'mongoose' );
var dbURI = 'mongodb://localhost/Loc8r';
mongoose.connect(dbURI);
// CONNECTION EVENTS
mongoose.connection.on('connected', function () {
console.log('Mongoose connected to ' + dbURI);
});
mongoose.connection.on('error',function (err) {
console.log('Mongoose connection error: ' + err);
});
mongoose.connection.on('disconnected', function () {
console.log('Mongoose disconnected');
});
I am expecting to get
Express server listening on port 3000
Mongoose connected to mongodb://localhost/Loc8r
But instead get:
Mongoose disconnected
Mongoose connection error: Error: failed to connect to [localhost:27017]
I've tried changing a line to var dbURI = 'mongodb://localhost:3000/Loc8r'; because that's what my computer is using, but then get this error:
Mongoose disconnected
Mongoose connection error: Error: connection closed
Any help is much appreciated thanks.
Mongo was missing the folders it needed MongoDB not working. "ERROR: dbpath (/data/db) does not exist."
Then the server had to be run with "mongod"
Im learning Node and trying create a server using Express and connecting it to a postgres db and keep getting the following when I run node server.js:
events.js:72
throw er; // Unhandled 'error' event
^
error: role "username" does not exist
at Connection.parseE (/Users/rs/Desktop/Jobletics/node_modules/pg/lib/connection.js:526:11)
at Connection.parseMessage (/Users/rs/Desktop/Jobletics/node_modules/pg/lib/connection.js:356:17)
at Socket.<anonymous> (/Users/rs/Desktop/Jobletics/node_modules/pg/lib/connection.js:105:22)
at Socket.emit (events.js:95:17)
at Socket.<anonymous> (_stream_readable.js:764:14)
at Socket.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:426:10)
at emitReadable (_stream_readable.js:422:5)
at readableAddChunk (_stream_readable.js:165:9)
at Socket.Readable.push (_stream_readable.js:127:10)
my server.js file looks like this:
// app dependencies
var express = require("express");
var Sequelize = require("sequelize");
var bodyParser = require('body-parser');
var morgan = require('morgan');
var app = express();
//middleware
app.use(bodyParser());
app.use(morgan('dev'));
//sequalize initialization
var sequelize = new Sequelize("postgres://username:password#localhost:5432/jobletics");
var employerRoute = require("./routes/employer")(sequelize);
//sync the model with the database
sequelize.sync().success(function (err) {
app.get("/employer", employerRoute.get);
app.post("/employer", employerRoute.create);
app.listen(5000);
});
I have postgres running. Do I need to create a new db in the command-line then run $psql to create username/password? Shouldn't the db get created automatically?
You can use
var sequelize = new Sequelize("postgres://username:password#localhost:5432/jobletics");
for connecting to postgresql database, but sequelize does not create nor user nor database for you. You must do it yourself. Use createuser and createdb postgres utilities to create them, or user -c flag of psql command. You also must have privilege to do it, so in the next example commands run using postgres user:
su postgres -c "psql -U postgres -c \"CREATE USER username WITH ENCRYPTED PASSWORD 'password'\""
su postgres -c "psql -U postgres -c \"CREATE DATABASE jobletics WITH OWNER=username ENCODING='UTF8'\""
Although Sequelize does not have a method to create databases, you can use the create query method to execute a custom method.
But the catch is the following,
You need to "connect to a database" to execute any command
Here you can't do that because it's that database creation command that you would want to create in the first place.
There's one simple way to overcome this. Postgress has two inbuilt template DBs that cannot be dropped called template0 and template1 respectively. More on template databases here
So all you have to do is connect to template1 (not template0) in your connection string
const sequelize = new Sequelize('postgres://username:password#localhost:5432/template1')
and execute the sequelize query method with the create query command
const createQuery = "CREATE DATABASE YOUR_DB_NAME WITH OWNER = postgres ENCODING = 'UTF8' LC_COLLATE = 'English_United States.1252' LC_CTYPE = 'English_United States.1252' TABLESPACE = pg_default CONNECTION LIMIT = -1;"
sequelize.query(createQuery)
.then(() => console.log("DB created"))
.catch(err => console.log("error creating DB", err))
I have not seen the database getting created automatically. When I use sequelize.js, i normally run it within a vm which has a puppet manifest to assert that the database already exists.
Also, when it comes to connecting to the db, I would normally do it like so as I think it is easier to read:
var Sequelize = require("sequelize");
var sequelize = new Sequelize(
"dbName",
"username",
"password",
{
"dialect": "postgres",
"port": 5423
}
);
Finally, make sure that postgres existing in your package.json, if is doesn't you will have to run the following:
npm install --save pg pg-hstore