2016-03-23 5 views
2

私はノードを初めて使用しており、mongoDBからデータを正常に読み取っています。ノードのmongoDBからのコレクション結果の保存

しかし、コレクションからのデータ全体をnodejsの変数に格納したいので、インデックスページで使用したいと思います。

保存方法がわかりません。

// Connection URL 
var url = 'mongodb://localhost:27017/test'; 

// Use connect method to connect to the Server 

MongoClient.connect(url, function (err, db) { 
    assert.equal(null, err);  
    console.log("Connected correctly to server"); 
    seriescollection = db.collection('series');  
}); 

var findseries = function (db, callback) { 
    var cursor = db.collection('series').find(); 
    cursor.each(function (err, doc) { 
     assert.equal(err, null); 
     if (doc != null) { 
      console.dir(doc); 
     } else { 
      callback(); 
     } 
    }); 
}; 
MongoClient.connect(url, function (err, db) { 
    assert.equal(null, err); 
    //insertDocument(db, function() {}); 
    findseries(db, function() { 
     db.close(); 
    }); 
}); 

MongoDBの中に私のサンプルJSONオブジェクトは、私はすべてのフィールドにアクセスして、私が保存されているフィールドに基づいてページを作成したい

{ 
    "_id" : "b835225ba18", 
    "title" : "Name", 
    "imageurl" :"https://promotions.bellaliant.net/files/Images/TMN/Ballers-June2015.jpg", 
    "namespaceId" : "UNI890" 
} 

です。私はすべてのフィールドにアクセスする必要があり、それが私の主な目標です。

これは、MEANのスタックを少しでも学ぶために余暇に取り組んでいるペットプロジェクトです。

ご協力いただきありがとうございます。

答えて

2

あり、このコードを持ついくつかの問題だが、私は何を探していることはtoArray方法だと思います。ここhttps://docs.mongodb.org/manual/reference/method/cursor.toArray/

そして:ここ

var findseries = function (db, callback) { 
    db.collection('series').find().toArray(function(err, allTheThings) { 

    // Do whatever with the array 

    // Spit them all out to console 
    console.log(allTheThings); 

    // Get the first one 
    allTheThings[0]; 

    // Iterate over them 
    allTheThings.forEach(function(thing) { 
     // This is a single instance of thing 
     thing; 
    }); 

    // Return them 
    callback(null, allTheThings); 
    } 
} 

もっとhttps://mongodb.github.io/node-mongodb-native/api-generated/cursor.html#toarray

+1

ありがとうあなたの助け。私は[オブジェクトのオブジェクト]としてallofthingsを取得.....完全な配列ではありません –

+0

ああgezz、それは私のばかだった。それはおそらく約束なのです。ここで説明するように、コールバックが必要です。https://mongodb.github.io/node-mongodb-native/api-generated/cursor.html#toarrayコードを更新しました。 –

+0

ありがとう!!うまく動作します –

関連する問題