The following code is the default async run function for the MongoDB JS driver.
async function run() {
try {
await client.connect();
const database = client.db('sample_mflix');
const movies = database.collection('movies');
// Query for a movie that has the title 'Back to the Future'
const query = { title: 'Back to the Future' };
const movie = await movies.findOne(query);
console.log(movie);
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
Is there any way on earth to do the CRUD operations etc outside of that function, e.g in an expressjs endpoint?
Thanks.
You can have a function that connects to the DB, probably in a different file and export the function
// DB.js
async function connectToDatabase() {
try {
await client.connect();
return client.db('sample_mflix');
} catch(err) {
console.dir(err);
} finally {
await client.close();
}
}
Then import it if you're using the export method, or just call the function
app.get('/api/path', () => {
const db = await connectToDatabse();
if (db) {
const query = {
title: 'Back to the Future'
};
const movie = await db.collection('movies').findOne(query);
console.log(movie)
}
})