D
D
dicem2021-03-23 15:39:52
MongoDB
dicem, 2021-03-23 15:39:52

How to correctly process requests to MongoDB in Express?

Hello, the question arose regarding the best practices in the mongodb + express stack, namely, how to handle writing, reading, etc.
Looked at get started from mongodb and wrote the following methods:

module.exports = {
    async create (client, data, entity) {
        try {
            await client.connect()
            await client.db('game').collection(entity).insertOne(data)
        } finally {
            await client.close
        }
    },
    async get (client, entity) {
        try {
            await client.connect()
            const cursor = await client.db('game').collection(entity).find({})
            return cursor.toArray()
        } finally {
            await client.close
        }
    },
    async update (client, entity, data, id) {
        try {
            await client.connect()

            const result = await client.db('game').collection(entity).updateOne(
                { id: id },
                { $set: data },
                err => {
                    if (err) console.log(err)
                }
            )

            console.log(result)
        } finally {
            await client.close
        }
    },
    async delete (client, id, entity) {
        try {
            await client.connect()
            const result = await client.db('game').collection(entity).deleteOne({ '_id': ObjectId(id) })
            return result
        } finally {
            await client.close
        }
    }
}


It can be seen that for each get / post / put / delete we connect to the database and close the connection at the end. However, with this approach, it will be very easy to use up a quota of 500 connections per day, even at expensive tariffs that give 3000 connections per day, with 10-30 users, these quotas will not be enough for the application even for a day of using the database.
So the question is, is this the right approach? Or is there an option to connect once and use this connection in the future for all operations on the database? and how to organize it in the code in this case?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question