处理ejs文件的mongodb数据的最佳方法

时间:2017-07-29 12:27:52

标签: node.js mongodb asynchronous ejs

我想主要渲染mongoDB数据和数组。我想要做的是允许我的ejs文件使用数据库中的组件。 这是我的代码:

 //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
 });

这是不正确的,因为它没有及时将所有数据推送到数据库数组,因为代码是异步的。我的问题是有更好的方法来访问要在ejs文件中使用的数据库数据,或者我必须找到一种方法将架构数据推送到数据库阵列并将其与restArray数据一起呈现。 (我需要restArray)。我希望在这个chart.js中使用mongoDB数据,这个数据位于我的ejs文件中:

<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>

1 个答案:

答案 0 :(得分:1)

开始使用ECMAScript 6生成器。所以你的代码看起来是同步的,Generators + co为你做了异步魔术。请在此处详细了解http://mongoua.tk/presentations/ecmascript-6-and-the-node-driver

使用Generators + co,您的代码看起来像这样

var co = require('co');

var databaseArray = [];
co(function*() {
  var record = yeild Restaurant.findOne({nameOfRest:this.nameOfRest});
  if(!record){
    record =  yeild Restaurant.save(this);
  }
  databaseArray.push(record);
  // do other operations....
  res.render('restaurant',{restHTML:restArray});
}).catch(function(err) {
  console.log(err.stack);
  res.status(500).send(err);
});