Below code check coming connection authenticated or not
..............
..............
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
....................
.....................
above connection process only display the "error" in command prompt not response the user. How to response the client(connection error) ?
Not sure what is most popular or to best to learn, the expressjs website hello world example is about responding to a "/" path 'get' http request.
In your web app example code and using express.js, you might be checking sequelize for a database connection on each request, in which case you would do something like:
app.get('/', function(res, req) {
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
//and do something like
//send data to the client
})
.catch(err => {
console.error('Unable to connect to the database:', err);
//
res.send('Unable to connect to the database.');
});
});
This express.js documentation about basic routing might also be useful.
Related
Beginner to redis here.
I'm trying to CRUD data from a distant redis server but I don't seem to make it work :
First we connect to the server :
const client = redis.createClient("the PORT", "the host", {auth_pass: "the password"});
(async () => {
try {
await client.connect();
console.log('Connected to redis');
} catch (err) {
console.error(err)
}
})()
The connection seems to work, as I receive a
Connected to redis in my terminal
But when I try to add data, it doesn't seem to work
app.get('/redis', (req, res) => {
// set name to antoine on redis
client.set('name', 'antoine', redis.print);
// get name from redis
client.get('name', (err, name) => {
res.send(name);
}
);
});
The endpoint just load indefinitely as if it doesn't do the
client.get('name', (err, name) => {
res.send(name);
}
);
And in my redis GUI, it shows No keys to display., so it didn't create the key either.
What am I missing here ?
EDIT : I just realized that instead of connecting to the distant server, I was connecting to my local one somehow.
Then, it seems that it doesn't connect to the distant.
EDIT2 : I forgot the async connect function, this is why it didn't work !
I have seen this issue published in a few places however I still don't have a solution.
I am using a node server and can connect to my database correctly with a status of 1 for connected.
However when I send requests to the mongodb database, the request pends and times out.
I have tried adding my IP to mongodb, putting my connection in an async function. and also removing mongoose and re installing it.
My structure is like this
app
client
node_modules > mongoose 5.13.14
server
node_modules > mongoose 5.13.14
My connection to mongodb is like this.
mongoose.connect(process.env.MONGOOSE_CONNECTION, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true })
.then(res =>{
console.log("Connected to Database")
}).catch(function (reason) {
console.log('Unable to connect to the mongodb instance. Error: ', reason);
});
An example of an endpoint that fails is here.
router.get('/therapists', (req, res) => {
signUpTemplate.find({}, (err, result) => {
if (err) {
console.log(err)
} else {
res.status(200).send({
results: result
})
}
})
})
which results in error
MongooseError: Operation therapists.find() buffering timed out after 10000ms
Can someone help me please as I am really not sure what the solution is.
Thank you!
I am trying to perform an axios request to the database from the socket.io server side, but am keep getting an error. How can I send Axios request or maybe there is a way to manipulate DB directly from socket.
socket.on('disconnect', reason => {
axios.get(`/api/rooms/${roomId}`)
.then(room => {
console.log(room);
socket.to(roomId).emit("disc", user)
})
.catch(err => console.log(err))
});
EDIT
So I actually ended up using mongoose query, which did the trick
Room.findOne({ _id: roomId})
.then(room => {
const filteredPlayers = room.players.filter(player => player !== user);
room.players = filteredPlayers;
room.save({players: room.players});
})
I have a mongoose connection to a mongodb server. When the server is running and it tries to connect it works fine and only prints out the single statement to the console. But when I haven't turned the mongo server on yet it prints both statements in the order they are in the code. I know this is not a huge error but would like to not have the health check show up as 'up' when the server is actually down.
Mongoose connection code:
mongoose.connect(config.db, {autoReconnect: true}, () => console.log('MongoDB has connected successfully.'));
mongoose.connection.on('error', function() {
console.error('MongoDB Connection Error. Make sure MongoDB is running.');
});
The connect callback receives an error parameter you can check:
mongoose.connect(config.db, {autoReconnect: true}, (err) => {
if (!err) console.log('MongoDB has connected successfully.');
});
You can also separately handle the 'connect' event in the same way you're handling the 'error' event:
mongoose.connection.on('connect', function() {
console.error('MongoDB has connected successfully');
});
I'm building a small web application using Node.js, Express, Mongoose, and Passport. Everything is working, but I'm trying to make the application fail gracefully if the MongoDB user database is not available. The application makes a database call every time it deserializes the user out of the session, so I can't do much if the database is down. I just want to display a general error page to the user and recover if/when the database is back up.
Right now, in my local implementation, if I take down the MongoDB server (by just hitting CTRL-C) and then try to, say, reload a page with authentication, sometimes I get my global error page but mostly the application just hangs without generating any errors or console logs (despite the addition of multiple console.log() statements at key failure points, see below) and continues to hang on all future requests. If I then restart the MongoDB server, the application doesn't recover.
The complete source code is here but select code snippets are below.
Mongoose connection:
mongoose.connect(mongodbURI, mongodbConnectOptions);
// Log database events to the console for debugging purposes
mongoose.connection.on('open', function () {
console.log("Mongoose open event");
});
mongoose.connection.on('close', function () {
console.log("Mongoose close event");
});
mongoose.connection.on('connected', function () {
console.log("Mongoose connected event");
});
mongoose.connection.on('disconnected', function () {
console.log("Mongoose disconnected event");
});
mongoose.connection.on('error',function (err) {
console.log("Mongoose error event:");
console.log(err)
});
The Passport deserializeUser() call:
passport.deserializeUser(function(id, done) {
console.log("Attempting to deserialize user")
User.findById(id, function(err, user) {
if (err) console.log("Database error inside deserializeUser()");
done(err, user);
});
});
The global error handler (installed at the end of the Express stack):
var errorHandler = function(err, req, res, next) {
console.log("Error caught by Express error handler")
console.log(err);
res.status(500);
res.render('error', { error: err });
}
app.use(errorHandler);
I think this is probably related to this question, but I'm specifically trying to handle the case when the connection is completely lost (because the database is down). Suggestions?