Answer the question
In order to leave comments, you need to log in
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
}
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question