I tried to connect to my db but it keep on returning that the collection is undefined even though I already declared it as a global variable. Not really sure what the closure issue is.
const express = require('express');
const app = express();
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
let db;
MongoClient.connect('mongodb://localhost:27017/todos', { useUnifiedTopology: true }, (err, client) => {
assert.equal(nul, err);
db = client.db('todos');
db.collection('todos').insertMany([
{ done:true, desc: 'write code'},
{ done:true, desc: 'write code'},
{ done:true, desc: 'write code'},
]);
client.close();
})
app.get('/', (req, res) => {
res.json('did this work!');
});
app.get('/todos', async (req, res) => {
const todos = await db.collection('todos').find().toArray();
res.json(todos);
});
app.listen(3001, () =>{
console.log("work pls");
});