I'm learning mongodb to create a API, and on every exemple or tutorial I see about using mongodb on Node.JS with Express the logic starts with a client.connect
, the query is done and client.close()
is called. Is it really necessary to connect before every query ? Isn't it possible to make a connection for exemple when a user login ( first query ) , and then as i'm going to do lots of query's while the user is logged i don't need to establish a connect after all of them, if the user logoff, thats when i want to close the connection.
Another question, is there another type of call i can do to replace .toArray(function (err, result) {}
? It's returning all my data inside a array with a single element and i need to do result[0]
sometimes, which seems awkward.
const search = {
multiple: function (query, projection, callback) {
console.log('multiple was called');
client.connect(url, function (err, client ) {
if (err) throw err;
console.log('Connected to db');
const db = client.db(currentdb);
const collection = db.collection(currentcollection);
collection.find(query).project(projection)
.toArray(function (err, result) {
console.log('Result on the way');
if (err) throw err;
callback(result)
client.close()
});
});
}
};