0

Im trying to write an if statement in Node.js with some mongoose query but the if statement does not get executed correctly.

So I'm doing this:

    app.get('Job/GetJobs', function(req,res){ 
      if(JobDB.Find()==null){
        req.render('home.html');
      }
      else req.render('Job.html')
    })

But the above code works if it was in java but not in Node.js because req.render('home.html'); gets executed before JobDB.find() finishes.

1 Answer 1

1

Most functions in Node.js are asynchronous, so you need to use a callback:

app.get('Job/GetJobs', function(req,res){ 
    JobDB.find({}, function(err, result) {
        if(!result) req.render('home.html')
        else req.render('Job.html') 
    })
})

(you'll have to include some error handling there)

See the documentation: http://mongoosejs.com/docs/2.7.x/docs/finding-documents.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.