【问题标题】:Reading collection data succeeded and then throws error读取集合数据成功然后抛出错误
【发布时间】:2016-09-22 17:34:10
【问题描述】:

这是我的server.js

我正在尝试按名字和姓氏获取数据, 然后传递数据并记录名字:

mongoDb.getFromDb(req.body.firstName, req.body.lastName)
  .then(
    rows => {
      rows.each(function(err, item) {
        console.log(item.firstName);
      })
    }
  )
});

mongoDb.js:

我有一个初始化函数,它创建了一个名为:connectingDb 的承诺。 它连接到数据库。

// Use connect method to connect to the Server
function init() {
  connectingDb = new Promise(
    function(resolve, reject) {
      MongoClient.connect(url, function(err, db) {
        if (err) {
          console.log('Unable to connect to the mongoDB server. Error:', err);
          reject(err);
        } else {
          console.log('Connection established to', url);

          //Close connection
          //db.close();
          resolve(db);
        }
      });

    }
  );
}

此函数获取名字和姓氏并根据这些条件返回行。

function getFromDb(firstName, lastName) {
  return new Promise(
    function(resolve, reject) {
      connectingDb.then(myDb => {
        console.log('a1a1a1');

        resolve(myDb.collection('alon').find({
          "firstName": firstName,
          "lastName": lastName
        }));

      }).catch(err => {
        console.log(err)
      })
    }

  )
}

这是我在`mongodb powershell'中写入的数据:

the data of the collection

错误是:

a
D:\Search\node_modules\mongodb\lib\utils.js:98
   process.nextTick(function() { throw err; });
                              ^
TypeError: Cannot read property 'firstName' of null

虽然a 是名字..

我猜函数 mongoDb.getFromDb 被调用两次是因为 promise。

任何帮助表示赞赏!

【问题讨论】:

    标签: javascript node.js mongodb


    【解决方案1】:

    rows 是否应该在rows.each 内更改为item
    也就是说,而不是

    ...
      rows.each(function(err, item) {
        console.log(rows.firstName);
      })
    ...
    

    更多类似

    ...
      rows.each(function(err, item) {
        console.log(item.firstName);
      })
    ...
    

    更新:另外你可能想使用forEach 而不是each 像这样

    getFromDb(firstName, lastName)
      .then(
        rows => {
          rows.forEach(function(item) {      
            console.log(item.firstName);
          })
        }
      );
    

    【讨论】:

    • 对不起,我的错。我在发布帖子并对其进行更改后看到了它,但是我得到了同样的错误(我重新启动了服务器)..
    • 是的,它有效!我将阅读每个到 forEach 之间的区别.. 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-15
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    相关资源
    最近更新 更多