你在你的代碼變得因爲Node.js的異步性質不明確的值,無處存在,告訴的console.log語句要等到find()
語句完成它打印出的文件之前的邏輯。你必須瞭解的callbacks在Node.js的概念這裏有一些問題,但是,你可以修復。很多人開始使用節點有傾向巢大量的匿名功能,創造了可怕的「末日金字塔」或callback hell。通過分解一些函數並命名它們,你可以使它更清晰和更容易遵循:
var MongoClient = require("mongodb").MongoClient
// move connecting to mongo logic into a function to avoid the "pyramid of doom"
function getConnection(cb) {
MongoClient.connect("your-mongo-url", function(err, db) {
if (err) return cb(err);
var accounts = db.collection("accounts");
cb(null, accounts);
})
}
// list all of the documents by passing an empty selector.
// This returns a 'cursor' which allows you to walk through the documents
function readAll(collection, cb) {
collection.find({}, cb);
}
function printAccount(account) {
// make sure you found your account!
if (!account) {
console.log("Couldn't find the account you asked for!");
}
console.log("Account from Array "+ account);
}
// the each method allows you to walk through the result set,
// notice the callback, as every time the callback
// is called, there is another chance of an error
function printAccounts(accounts, cb) {
accounts.each(function(err, account) {
if (err) return cb(err);
printAccount(account);
});
}
function get_accounts(cb) {
getConnection(function(err, collection) {
if (err) return cb(err);
// need to make sure to close the database, otherwise the process
// won't stop
function processAccounts(err, accounts) {
if (err) return cb(err);
// the callback to each is called for every result,
// once it returns a null, you know
// the result set is done
accounts.each(function(err, account) {
if (err) return cb(err)
if (hero) {
printAccount(account);
} else {
collection.db.close();
cb();
}
})
}
readAll(collection, processAccounts);
})
}
// Call the get_accounts function
get_accounts(function(err) {
if (err) {
console.log("had an error!", err);
process.exit(1);
}
});
你是怎麼調用'get_accounts()'函數的? – chridam
只是注意到在[mongolabs]環境空間中定義了[process.env.MONGOLAB_URI]。你通常會使用這個對比一些「網址」。 –