Maria Maldini Maria Maldini - 1 year ago 47
Node.js Question

Reading collection data succeeded and then throws error

This is my

server.js
:

I'm trying to get the data by firstName and lastName,
then passing the data and log the firstName:

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


mongoDb.js
:

I have an init function that creates a promise that is called:
connectingDb
.
It connects to the DB.

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

}
);
}


This function gets first name and last name and returns the rows by those conditions.

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

)
}


And this is the data when I write it in `mongodb powershell':

the data of the collection

The error is:

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


While
a
is the first name..

I guess the function
mongoDb.getFromDb
is called twice because of the promise.

Any help appreciated!

Answer Source

Should rows maybe changed to item within rows.each?
That is, instead of

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

more something like

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

Update: In addition you probably want to use forEach instead of each like so

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