Javascript动态参数,并将查询结果保存到它

时间:2016-06-07 14:26:45

标签: javascript mysql node.js dynamic parameters

我是javascript和节点的新手,我在这个上面遇到了困难。我已尝试过在动态创建对象的问题上提出的解决方案,但现在问题是将查询保存到其中。

所以一般来说,我有一个餐厅,有一个菜单,有类别,有产品。因此,我收到一个Restaurant_id,找到它的菜单,然后是它的类别,最后是每个类别的产品。我从第二个查询开始,因为我已经想到了其他一切。

connection.query("SELECT id_section, name FROM menu_section WHERE id_menu = ?", [id_menu], function(err, results) {

      if(err){
        console.log(err);
      }
      console.log("Result 2nd query " + JSON.stringify(results));
      //^^ this logs: Result 2nd query [{"id_section":1,"name":"Beverages"},{"id_section":2,"name":"Breakfast"}]

      var size = results.length;
      var id_section = [];

      for(var i = 0; i < size ; i++){
        result_menu[results[i].name] = ""; //this creates the object named result_menu with first parameter Beverages and 2nd breakfast
        params[i] = results[i].name;
        console.log("Inserted dynamic params: " + params[i]); // this logs Beverages, and Breakfast
        id_section[i] = results[i].id_section; //this saves the ID of each sections in that menu so I know what to query next
        console.log("Inserted ID's" + id_section[i]); //this logs 1 and 2, which are my section ID's

          connection.query("SELECT name, price FROM menu_product WHERE id_section = ? AND active = 1", 
          [id_section[i]], function(err, results2) {
            console.log(results2); //this log shows me that my query is right in both cycles: [ RowDataPacket { name: 'Heineken', price: 40 } ]
            result_menu[params[i]] = results2; // trying to insert first query on params[i] which contains "Beverages" and "Breakfast" 
            console.log("value of : " + JSON.stringify(result_menu));
            //last log, logs: "value of : {"Beverages":"","Breakfast":"","undefined":[{"name":"Heineken","price":40}]}"    
          });

      }  
      connection.release();
      callback(result_menu); 
    });

很抱歉长代码,但似乎有必要。问题是......我已经动态创建了参数,但是Postman给了我下一个结果,并且日志中显示的创建的“undefined”参数甚至没有显示在回调中:

{
  "Beverages": "",
  "Breakfast": ""
}

我真正想要建立的是:

{
  "Beverages": [{"name": "Heineken", "price": "45"}, {"name": "Coke", "price": "10"}],
  "Breakfast": [{"name": "Eggs", "price": "65"}, {"name": "Pancakes", "price": "70"}]
}

我不知道,为什么js没有保存查询结果......我该怎么办呢?有什么想法吗?

0 个答案:

没有答案