0

コレクション内の要素の正数を取得できます...

var collection;

collection = db.collection("allCodes");

collection.count(function(err, count) {
  if (err) {
    throw err;
  }
  console.log("There are " + count + " records.");
});

...出力付き:

Connected to Database ok
There are 354 records.

...しかし、このコレクションの要素を取得できません:

collection.find().each(function(err, doc) {
  if (err) {
    throw err;
  }
  console.log("each doc");
  console.log(doc);
});

...何も出力しません。私はmongodbが初めてです。それで、私は何を間違っていますか?allCodesコレクション内のすべての要素を印刷したい。

更新: データを挿入するすべてのコードはカウントを取得し、データ自体をフェッチしようとしますが、何も出力されません。

var MongoClient, collection;

MongoClient = require("mongodb").MongoClient;
var objectToInsert = [{
    'a': 1
}, {
    'a': 2
}, {
    'b': 3
}]
MongoClient.connect("mongodb://127.0.0.1:27017/test", function(err, db) {
    console.log("Connected to Database");
    collection = db.collection("test2");
    // clear collection -------------------------------
    collection.remove(function(err, result) {
        // insert ------------------------------------
        collection.insert(objectToInsert, function(docs) {
            // count - ok -----------------------------------
            collection.count(function(err, count) {

                console.log("Count: " + count);
                // find - fail - no objects printed -----------------------
                collection.find().toArray(function(err, docs) {
                    console.log("Printing docs from Array");
                    docs.forEach(function(doc) {
                        console.log("Doc from array");
                        console.log(doc);
                    });
                });
                db.close();

            });

        });
    });
});

出力があります:

Connected to Database
Count: 3

では、なぜ私は数えるしかないのですか。私のデータはどこにありますか?

4

2 に答える 2

0

免責事項:私はにまったく精通していません。

ドキュメントの例から、最初にカーソル オブジェクトを作成し、後で結果を反復処理する必要があるようです。コマンドの連鎖についてどのような考慮事項があるのか​​ わかりません。

var cursor = collection.find();

// Execute the each command, triggers for each document
cursor.each( function( err, item ) {
  console.log( "each doc" );
});
于 2013-10-13T08:59:47.757 に答える