Mongodb 查找 () returns 未定义 (node.js)

Mongodb find() returns undefined (node.js)

我在 node.js 中一直在玩 mongodb。我用一些数据做了一个基本的收集(我知道它已经检查过了)。当我尝试 运行 集合上的 find() 时,它 returns 未定义。我不知道这是为什么。代码如下:

function get_accounts(){
    var MongoClient = mongodb.MongoClient;
    var url = "url";

    MongoClient.connect(url, function (err, db) {
      if (err) {
        console.log('Unable to connect to the mongoDB server. Error:', err);
      } else {
        //HURRAY!! We are connected. :)
        console.log('Connection established to database');
        var collection = db.collection('accounts');
        collection.find().toArray(function(err, docs) {
          console.log("Printing docs from Array")
          docs.forEach(function(doc) {
            console.log("Doc from Array ");
            console.dir(doc);
          });
        });
        console.log("mission complete");
        }
        db.close();
    }
  );
}

如果您知道为什么会这样,我想听听您的想法。谢谢!如果有任何区别,该数据库是一个 mongolab 托管的数据库。

您可能需要在查找中添加一个空的 JSON 对象。

collection.find({})

可以找到文档 here

由于 node.js 的异步性质,您得到了一个未定义的值,您的代码中没有任何地方存在告诉 console.log 语句等到 [=11] 的逻辑=] 语句在打印出文档之前完成。你要明白callbacks in Node.js. There are a few problems here, though, that you could fix. A lot of people getting started with node have the tendency to nest lots of anonymous functions, creating the dreaded "pyramid of doom" or 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);
     }
});

您必须在异步函数中输入此代码,这里的数据是您想要的值,并且您必须使用 promises 以免代码看起来混乱。

var accountCollection = db.collection('accounts);
let data = await accountCollection.find().toArray.then(data=>data).catch(err=>err);