title: Mongo-atlas connection : ReferenceError: client is not defined
body: <p>when trying to connect to the mongo atlas I'm getting the error "ReferenceError: client is not defined".</p>
  
  <blockquote>
    <p>Console's erro :</p>
    
    <p>const db = client.db('coneccao-teste');
                ReferenceError: client is not defined</p>
  </blockquote>
  
  <p>See below my NodeJs code with the configuration of the Express server and mongo-atlas connection.</p>
  
  <p>Have you sugestion ?</p>
  
  <p>thanks!</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const express = require('express');
  const app = express();
  const router = express.Router();
  const MongoClient = require('mongodb').MongoClient;
  const ObjectId = require('mongodb').ObjectId;
  const port = 3000;
  const mongo_uri = 'mongodb+srv://rbk:******-@cluster0-5zvdy.mongodb.net/coneccao-teste?retryWrites=true';
  const db = client.db('coneccao-teste');
  const collection = db.collection('inicio');
  
  
  MongoClient.connect(mongo_uri, { useNewUrlParser: true })
  .then(client =&gt; {
    const db = client.db('coneccao-teste');
    const collection = db.collection('inicio');
    app.listen(port, () =&gt; console.info(`REST API running on port ${port}`));
  }).catch(error =&gt; console.error(error));
  
  // add this line before app.listen()
  app.locals.collection = collection;
  
  app.get('/', (req, res) =&gt; {
    const collection = req.app.locals.collection;
    collection.find({}).toArray().then(response =&gt; res.status(200).json(response)).catch(error =&gt; console.error(error));
  });
  
  app.get('/:id', (req, res) =&gt; {
    const collection = req.app.locals.collection;
    const id = new ObjectId(req.params.id);
    collection.findOne({ _id: id }).then(response =&gt; res.status(200).json(response)).catch(error =&gt; console.error(error));
  });
  
  
  app.listen(port);</code></pre>
  </div>
  </div>
  </p>