0

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()
                });
        });
    }
};
Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Bruno Cerk
  • 355
  • 3
  • 16
  • 1
    Why? Wherever you are learning this from, throw that source away and start learning from somewhere else. You NEVER open and close database connections per request. And for the "other question" there's a `findOne()` method which returns only one when that is what you expect. Just remember the format is "Question" and "Answers" not "Question**s**". You get to ask one at a time, and asking multiple "questions" is more likely to get your "questions" closed as too broad anyway. – Neil Lunn Jun 15 '18 at 04:29
  • Thanks for that =) i'll dig deeper into it – Bruno Cerk Jun 15 '18 at 04:37
  • Those examples are usually meant to just show one individual query - not an ongoing ‍♂️ process. – CodeFinity Mar 23 '21 at 01:06

0 Answers0