Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

208
Views
Why am I keeping getting 'Collection is undefined' error on MongoDb

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");
}); 
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!