【问题标题】:Mongodb find() returns undefined (node.js)Mongodb find() 返回未定义(node.js)
【发布时间】:2020-09-26 19:03:30
【问题描述】:

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

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 托管的数据库,如果这有什么不同的话。

【问题讨论】:

  • 你是怎么调用get_accounts()函数的?
  • 请注意 [process.env.MONGOLAB_URI] 是在 mongolabs 环境空间中定义的。你通常会使用这个而不是一些“url”。

标签: javascript node.js mongodb mlab


【解决方案1】:

由于 node.js 的异步特性,您获得了一个未定义的值,您的代码中没有任何地方存在告诉 console.log 语句等到 find() 语句在它之前完成的逻辑打印出文件。您必须了解 Node.js 中 callbacks 的概念。不过,这里有一些问题可以解决。许多刚开始使用 node 的人倾向于嵌套大量匿名函数,从而创建了可怕的“末日金字塔”或 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);
     }
});

【讨论】:

  • 在我经历过的这么多 SO 答案中,最干净的答案是非常合适的 cmets。谢谢。
【解决方案2】:

您可能必须在查找中添加一个空 JSON 对象。

collection.find({})

可以在here找到文档。

【讨论】:

  • 从这个控制台你看到了什么:console.log("Array:", collection.find().toArray())
  • 我的错。你检查过err 有没有东西?我认为你到达console.log("Printing docs from Array")
【解决方案3】:

您必须在异步函数中输入此代码,这里数据是您想要的值,您必须使用承诺不会让您的代码看起来混乱。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-05
    • 2017-10-08
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 2016-05-01
    相关资源
    最近更新 更多