我正在尝试创建一个函数来查询MongoDB数据库中的数据,并以数组的形式返回所有对象。这是我的代码:
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert')
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/stuff'; //database from which to select is at the end of the path
var myArray = [];
function findStuff(db) {
var cursor =db.collection('images').find( );
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
console.dir(doc);
myArray.push(doc);
console.log(myArray.length)
} else {
db.close();
console.log("Done with function...");
}
});
};
这是我写的一个测试,看看findStuff是否正确地将myArray设置为集合中对象的数组:
MongoClient.connect(url, function(err, db) {
findStuff(db);
console.log("Length of myArray:");
console.log(myArray.length);
for (var i = myArray.length - 1; i >= 0; i--) {
console.log(myArray[i]);
console.log("Hello"); //This is here to show that the for-loop runs
};
});
当我使用Node运行代码时,我得到以下内容:
Length of myArray:
0
{ _id: { _bsontype: 'ObjectID', id: 'U2eCs/®\tÿ$' },
id: 1,
name: 'Tree with sunset 0',
url: 'http://goo.gl/TgH49m' }
1
{ _id: { _bsontype: 'ObjectID', id: 'U2ÇCs/®\tÿ%' },
id: 2,
name: 'Hills n Clouds',
url: 'http://goo.gl/VXjdSa' }
2
{ _id: { _bsontype: 'ObjectID', id: 'U;\'ó\u0010oiÒ\u001cé' },
id: 3,
name: 'Hammock 1',
url: 'http://goo.gl/CBO3cf' }
3
Done with function...
为什么在findStuff中调用console.log之前调用console.log(" MyArray的长度:")和console.log(myArray.length)? for循环从不做任何事情,因为输入循环时myArray的长度为0。为什么在调用findStuff之前会出现for循环?或者findStuff实际上没有改变myArray的值?无论哪种方式,我都被困住了。发生了什么事?
答案 0 :(得分:1)
问题是db.collection('images').find()
是异步执行的。这意味着它将排队等待下次没有其他运行。因此,在您拨打其余代码之前,db.collection('images').find(function(err, results) {
...
});
没有机会完成。
在检索数据后运行一些代码provide a callback。
{{1}}