簡體   English   中英

Mongodb find() 返回 undefined (node.js)

[英]Mongodb find() returns undefined (node.js)

我一直在 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 托管的數據庫。

由於 node.js 的異步性質,您得到了一個未定義的值,您的代碼中沒有任何地方存在告訴 console.log 語句等待find()語句完成后再打印文檔的邏輯。 您必須了解 Node.js 中回調的概念。 但是,這里有一些問題可以解決。 很多剛開始使用 node 的人都傾向於嵌套大量匿名函數,從而造成可怕的“末日金字塔”或回調地獄 通過拆分一些功能並命名它們,您可以使其更清晰,更易於遵循:

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);
     }
});

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

collection.find({})

文檔可以在這里找到。

您必須在 async 函數中輸入此代碼,在這里 data 是您想要的值,並且您必須使用 promise 不會讓您的代碼看起來很混亂。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM