6

私は node.js と heroku が初めてで、node.js を使用して mongodb インスタンスからデータを取得する小さなアプリを作成しました。私はすべてをセットアップしましたが、私の問題は、mongodb の単純な構文上の問題だと思います。

アプリの起動時に、コレクションに何かが含まれているかどうかを知る必要があります。そうでない場合は、初期化するだけです。collection.count() を呼び出してみましたが、undefined が返されます。

私はこれをやってみました

mongo.connect(mongoUri, {}, function(err, database) {
  if(!err) {
      db = database;
      console.log("Connected to 'testdb' database, HERE");
      db.collection('tests', {safe:true}, function(err, collection) {
          if (err) {
              console.log("The 'tests' collection doesn't exist. Creating it ");
              populateDB();//This would work for the first time I install the app on heroku
          }
          else { //Collection exists, but nothing is in it, this is where I am lost
             console.log("now I am HERE");
             //I do not know how to mimic this piece of code
             //if((collection("tests").find().toArray.size() == 0 or empty or the equivalent of it) {
             //    populateDB();
             //}
             console.log((collection("tests").find().toArray.size()));
          }
      });
  }
  else {
      console.log("COULD NOT CONNECT TO MONGO: " + mongoUri);
  }
});

どんな助けでも大歓迎です。

4

2 に答える 2

9

データベース内のデータにアクセスするすべての MongoDB ドライバー メソッド (countおよび などtoArray) は、単一の node.js スレッドをブロックしないように、戻り値ではなくコールバック関数パラメーターを介して呼び出し元に非同期的に結果を提供します。

したがって、チェックは次のようになります。

collection.count(function (err, count) {
    if (!err && count === 0) {
        populateDB();
    }
});
于 2013-05-24T21:34:04.260 に答える