从mongodb检索数据

时间:2016-06-23 09:28:51

标签: node.js mongodb heroku mongodb-query

问题是,我试图从mongodb获取我保存的数据并将其显示在表格中。

 using UnityEngine;
 using UnityEngine.SceneManagement;
 using UnityEngine.UI;
 using UnityEngine.Advertisements;
 using System.Collections;
 using System.Collections.Generic;
 using GooglePlayGames;
 using UnityEngine.SocialPlatforms;
 using GooglePlayGames.BasicApi;
 using UnityEngine.Analytics;

 public class Menu : MonoBehaviour {

 public Text record;

 /**
     Menu when the player isn´t authenticate
  */
 public GameObject signIn;

 public GameObject test;

 void Awake()
 {
     PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder ().Build ();
     PlayGamesPlatform.InitializeInstance(config);
     GooglePlayGames.PlayGamesPlatform.DebugLogEnabled = false;
     GooglePlayGames.PlayGamesPlatform.Activate ();
 }

 void Start()
 {
     Advertisement.Initialize ("CORRECT_NUMBER", true);


     if (PlayerPrefs.HasKey("record"))
     {
         record.text = "Record actual: " + PlayerPrefs.GetInt("record");
         Analytics.CustomEvent ("Start Play", new Dictionary<string, object>{ { "Record", PlayerPrefs.GetInt("record")} });
         if (Social.localUser.authenticated) 
         {
             Social.ReportScore (PlayerPrefs.GetInt ("record"), "CORRECT_CODE", (bool success) => { });
         }
     } else {
             record.text = "Consigue un record!!";
     }

     if (Social.localUser.authenticated) 
     {
         signIn.SetActive (false);           
     }
     test.SetActive (false);
 }

 public void OnPlay()
 {
     ShowAd ();
     SceneManager.LoadScene("Play");
     Time.timeScale = 0;
 }

 public void OnArchievements()
 {
     if (Social.localUser.authenticated) {
         Social.ShowAchievementsUI ();
     } else {
         Social.localUser.Authenticate ((bool success) => {
             if (success) {
                 Social.ShowAchievementsUI ();           
             }
         });
     }

 }

 public void OnMatching()
 {
     if (Social.localUser.authenticated) {
         Social.ShowLeaderboardUI ();
     } else {
         Social.localUser.Authenticate ((bool success) => {
             if (success) {
                 Social.ShowLeaderboardUI ();        
             }
         });
     }
 }

 public void OnExit()
 {
     Analytics.CustomEvent ("Stop Play", new Dictionary<string, object>{ { "Record", PlayerPrefs.GetInt("record")} });
     Application.Quit();
 }

 public void SignIn()
 {
     Social.localUser.Authenticate((bool success) => { 
         if (success)
         {
             Debug.Log ("Sign in");
             signIn.SetActive (false);
         }
         else
         {
             Debug.Log ("Fail for some reason...");
             test.SetActive (true);
         }

     });

 }

 public void Later()
 {
     signIn.SetActive (false);
 }

 public void ShowAd()
 {
     if (Advertisement.IsReady())
     {
         Advertisement.Show();
     }
 }
 }

这是一个应该从DB中检索数据的函数:

&#13;
&#13;
router.get('/page', function (req, res, next) {
     var VariableWithNoName = listAllResults();
     res.render('page', {title: 'page', dbresults: VariableWithNoName});  
});
&#13;
&#13;
&#13;

这是我的.hjs页面:

function listAllResults() {
  mongo.connect(process.env.MONGODB_URI, function(err, db) {
    assert.equal(null, err);
    var results = db.collection('mydatabase').find();
    var show = '<table>';
    results.each(function(err, result) {
      assert.equal(err, null);
      if (result != null) {
        show = show + '<tr><td>' + result['object']['BasicInfo[Name]'] + '</td></tr>';
      } else {
        callback();
      }

    });
    show = show + '</table>';
    return show;
  });
}

知道它有什么问题吗?

已编辑:

数据库结构:

<div id="ListOfResults">
    <p> Here there should be the list: </p>
    {{dbresults}}
</div>

1 个答案:

答案 0 :(得分:0)

没有结果,因为Node.js中MongoDB的结果是异步的。您的listAllResults()函数应该将回调作为参数,以便在调用函数时可以在路由器中使用该回调。

考虑重构代码以容纳异步函数:

异步功能

function listAllResults(callback) {
    mongo.connect(process.env.MONGODB_URI, function(err, db) {
        assert.equal(null, err);
        db.collection('mydatabase').find().toArray(function (err, results){
            if (err) throw err;         
            if (results != null) {
                var show = '<table>';
                results.each(function(err, result) {
                    show = show + '<tr><td>' 
                                + result['object']['BasicInfo[Name]'] 
                                + '</td></tr>';
                });
                show = show + '</table>';
                callback(show);
            }
            else {      
                // return empty table
                callback('<table></table>');
            }           
        });
    });
}

<强>路线

router.get('/page', function (req, res, next) {
    listAllResults(function (VariableWithNoName){
        res.render('page', {title: 'page', dbresults: VariableWithNoName}); 
    });     
});

有关如何从异步函数返回值的详细信息,请参阅以下两个问题: