0

In my JavaScript program, I would like to get the "Booking" collection fetched from MongoDB and then store the return value into a JavaScript variable.

router.get('/dashboard', function(req, res){
    //hardcode some value for testing, the program can pass this value.
    var booking = [{id: 1, name:"AAA"}, {id: 2, name:"BBB"}, {id: 3, name:"CCC"}];

    Booking.collection.find().toArray(function(err, docs) {
        console.log(docs);
        console.log("S-------------------------------------------------");
        // assign the returned value from collection to "booking" variable
        booking = docs; // Booking variable can store the value.
        console.log(booking); //can print the value here
        console.log("E-------------------------------------------------");
    });   

    // After execution of above statement, "booking" variable does not contain any value 
    // (because I cannot get the value after running the last code.)
    // Why?? How can I resolve it?

    // The "booking" variable does not contain value after execution of below code.
    res.render('dashboard', {booking:booking});
});

I can successfully get the return value but I have no idea how to store this value in my local JavaScript variable for further action.

Do anyone advise how to resolve this issue? Thank you.

1 Answer 1

1

Ok, the problem here is that the Mongoose action is asynchronous. So you should manage the booking data inside the callback

`

Booking.collection.find().toArray(function(err, docs) {
    if(!err){
       res.render('dashboard', {booking:docs});
   }
});   

`

I also recommend you as a good practice to manage all the database interaction (fetch, add ,delete ...) in a separate module. It could be a helper folder.

Helpers are 'general' helper objects (not feature specific) that execute 'static' functions that are useful throughout the entire application. For example, a function that manages string or date parameters, a function that parses the response of an ajax call, a function that manages proper cleanup of view objects, etc... https://www.quora.com/What-is-the-best-folder-structure-practice-for-Javascript-Backbone-related-to-delegate-helper-functions

And then manage their response with a callback function or promises.

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

2 Comments

Thanks, I solved the problems using your suggestion.
You are welcome. If you need anything else don't doubt to ask it.

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.