Mongodb find()返回未定义的(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);
     }
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

MongoDB返回“未定义”的node.js

来自分类Dev

Node.js从MongoDB获取请求返回未定义

来自分类Dev

MongoDB查找返回在Node.Js代码中未定义的结果

来自分类Dev

节点js从mongodb obejct内部值返回未定义

来自分类Dev

MongoDB返回未定义

来自分类Dev

Node.js“无法读取未定义的属性'prototype'”错误-Node.js,MongoDB和Angularjs书

来自分类Dev

Node.js Q承诺forEach返回未定义

来自分类Dev

Node.js NPM MSSQL函数返回未定义

来自分类Dev

node.js中返回的unirest响应未定义

来自分类Dev

模块函数在Node.js中返回未定义

来自分类Dev

Node.js解构变量返回未定义

来自分类Dev

Node.js NPM MSSQL函数返回未定义

来自分类Dev

Node.js Q承诺forEach返回未定义

来自分类Dev

node.js中返回的unirest响应未定义

来自分类Dev

node.js函数返回未定义的值

来自分类Dev

node.js返回未定义的问题

来自分类Dev

Node.js 表单值总是返回“未定义”

来自分类Dev

返回未定义的 JS

来自分类Dev

MongoDB排序返回未定义

来自分类Dev

调用未定义的方法MongoDB :: find()

来自分类Dev

JS函数返回未定义

来自分类Dev

简单的js FOR循环返回“未定义”

来自分类Dev

js函数调用返回未定义

来自分类Dev

Vue js方法返回未定义

来自分类Dev

MongoDB:为什么对注释(数组)属性的Array.find返回未定义?

来自分类Dev

未定义模块名称-Node js

来自分类Dev

变量未定义node.js

来自分类Dev

Require未定义node.js

来自分类Dev

未定义Node.js __dirname