1
\$\begingroup\$

I'd like to render mainly mongoDB data and an array. What I want to do is allow my EJS file to use the components inside the database.

 //Array to store all restaurants
 var restArray = [];

 //Need database restaurant schema 
 var databaseArray = [];

 //Find the restaurant in the database,
 //If not there create one.
 var findOrCreate = function() {
     Restaurant.findOne({
             nameOfRest: this.nameOfRest
         })
         .then(exist => {
             if (!exist) {

                 this.save()
                     .then(result => {
                         databaseArray.push(result);
                     })
                     .catch(err => {
                         console.log(err);
                     })
             } else {
                 databaseArray.push(exist);
             }
         })
         .catch(err => {
             debugger;
             console.log(err);
         })
 }
 //Go through each restaurant and put in function.
 restArray.forEach(function(restArr) {

     var tempRest = new Restaurant({
         nameOfRest: restArr.restaurant.name,
         favoriteFoods: [],
     });
     //databaseArray.push(tempRest);

     findOrCreate.call(tempRest);
 });
  //*****************I would use database array here 
 res.render('restaurant', {
     restHTML: restArray
 });

This is incorrect as it does not push all of it to the database array in time because the code is asynchronous. Is there a better way to access database data to be used in the EJS file or do I have to find a way to push the schema data into the databaseArray and render it alongside restArray data (I need the restArray)? I would like the mongoDB data to be put here:

<script>
window.onload = function()
{
    var ctx = document.getElementById("myChart").getContext('2d');
    var myChart = new Chart(ctx, 
    {
      type: 'bar',
    data: {
        labels: ["Chili dog", "Burger", "Zucchini Fries"], //*****************Put mongodb data inside here *******************
        datasets: [{
            label: 'Best food here:' ,
            data: [12, 19, 3], //********************Put mongodb data inside here. ******************
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
            ],
            borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
            ],
            borderWidth: 1
        }]
    },
    options: {
        responsive: false,
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }

    }
    }); 
}
</script>
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.