0

I am just starting Node Js. Here i am trying to insert users data. But an error showing "ReferenceError: usersCollection is not defined".

const express = require('express');
const bodyParser= require('body-parser')
const MongoClient = require('mongodb').MongoClientconst
app = express();
app.use(express.urlencoded({ extended: true }))
app.listen(3000);
var dburl = "mongodb://localhost:27017/";
MongoClient.connect(dburl)
 .then(db => {
    const dbo = db.db("mongojs");
    const usersCollection =dbo.collection('users')
 });
 app.get('/',function(request,response){
    response.sendFile(__dirname + '/views/register.html');
 });
 app.post('/auth', function(request,response{
   usersCollection.insertOne(request.body)
   .then(result => {
    console.log(result)
   })
  .catch(error => console.error(error))
});
Jyothi
  • 53
  • 8
  • Does this answer your question? [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Tobias S. Oct 22 '21 at 08:24
  • Yes. const have block scope. Thankyou @TobiasS. – Jyothi Oct 22 '21 at 08:34

1 Answers1

0

Fixed the issue

..........
 var usersCollection;
 var dburl = "mongodb://localhost:27017/";
 MongoClient.connect(dburl)
  .then(db => {
    dbo = db.db("mongojs");
    usersCollection = dbo.collection('users')
 });
Jyothi
  • 53
  • 8