So, when I first open the connection with the database, all is working fine, but when I close it and try to re-open it, the db object gives no error but returns undefined ...
Here's how I open the connection :
let conn = null;
let db = null;
async function validateLoginForm(payload, res) {
const errors = {};
let isFormValid = true;
let message = '';
if (!payload || typeof payload.email !== 'string' || payload.email.trim().length === 0) {
if (payload.email !== 'anonymous') {
isFormValid = false;
errors.email = 'Please provide your email address.';
}
}
if (!payload || typeof payload.password !== 'string' || payload.password.trim().length === 0) {
if (payload.email !== 'anonymous') {
isFormValid = false;
errors.password = 'Please provide your password.';
}
}
let stringConnection = payload.email === 'anonymous' ? 'mongodb://ds133221.mlab.com:33221/sandbox-te' : 'mongodb://' + payload.email + ':' +
payload.password + '@ds133221.mlab.com:33221/sandbox-te';
conn = await MongoClient.connect(stringConnection, await function(err, dbase) {
if (err)
{
isFormValid = false;
let errorMessage = 'Error connecting to DB';
return res.status(400).json({
success: false,
message: errorMessage,
errors: errors
});
}
else
{
db = dbase;
if (payload.email !== 'anonymous')
{
let roles = dbase.command({usersInfo: {user: payload.email, db: 'sandbox-te'}, showCredentials: true}, (err, result) => {
if (result.users[0] && result.users[0].roles[0] &&
(result.users[0].roles[0].role === 'dbOwner' || result.users[0].roles[0].role === 'readWrite'))
{
dbase.close();
return res.status(200).json({
success: true,
hasWriteRole: true
})
}
});
}
else
{
return res.status(200).json({
success: true,
hasWriteRole: false
})
}
}
});
}
The first part of the file validates a login form and the second part uses the email and password to try to open a connection with the database.
The whole function just works fine, but when I try to re-open it in the same file but another function, it won't work :
router.post('/search', (req, res) => {
db.open((err, dbase) => {
let test = dbase.collection('test');
console.log(test);
let promiseOfFind = test.find({}).toArray((err, docs) => {
console.log(docs); // RETURNS UNDEFINED ONLY IF DB WAS CLOSED EARLIER
})
});
});
If I don't close the database in the validateLoginForm function, I can retrieve documents without having to open it again, but I just want to achieve this..
What is wrong with my code ? I'm pretty new to Javascript and the API reference of the official MongoDB driver for node.js doesn't help much..
I'm using latest versions of React, Express, MongoDB official Driver for Node.JS, and of course, Node.JS
Thanks in advance !
db.open()looks like you are trying to access a deprecated method. The connection should always be open.