Search code examples
mongodbmongoose

ReferenceError: Cannot access 'list' before initialization


I am now working on a project where I am using mongoose, and I am facing an issue that I checked that if there is already a document available with the same name in my database what I searched for, If its available then return a that page if not available then create a new document with that name. But the main issues that in console its showing that

          **ReferenceError: Cannot access 'list' before initialization **

I am given my code and console view can someone suggets in which point I have to change.

in my app.js file ...........

app.get('/:customListName', function(req,res){
       const customListName=req.params.customListName;

       List.findOne({name:customListName}).then(function(foundList){

         // if(!err){
           if(foundList===null){
             const list= new list({
               name:customListName,
               items:foundItem
             });

             list.save();
             res.render('/'+customListName);
               console.log(foundList);
           }else{
               res.render("list", {listTitle: customListName, newListItems: foundItem});

           }
         

       });


});

but in console ......

C:\Users\suraj\Documents\Web development-2\todolist-v2-starting-files\app.js:79 const list= new list({ ^

ReferenceError: Cannot access 'list' before initialization at C:\Users\suraj\Documents\Web development-2\todolist-v2-starting-files\app.js:79:26 at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Node.js v18.13.0 [nodemon] app crashed - waiting for file changes before starting...

enter image description here

So can someone suggest some solution?


Solution

  • The answer is that I was supposed to use new List instead of new list.

    here is the code...............>

     app.get('/:customListName', function(req,res){
           const customListName=req.params.customListName;
    
           List.findOne({name:customListName}).then(function(foundList){
    
             // if(!err){
               if(foundList===null){
                 const list= new List({
                   name:customListName,
                   items:foundItem
                 });
    
                 list.save();
                 res.render('/'+customListName);
                   console.log(foundList);
               }else{
                   res.render("list", {listTitle: customListName, newListItems: foundItem});
    
               }
             
    
           });
    
    
    });