1

I am a noob with Node.JS. I am using CouchDB and Cradle. In couchDB I have a database named 'test' and inside it I have a document named 'exercise'. The document has 2 fields: "FullName" and "Age". The code in order to save the data is as follows:

var cradle = require('cradle');
var connection = new(cradle.Connection)('http://127.0.0.1', 5984, {
    auth: { username: 'toto_finish', password: 'password' }
});

var db = connection.database('test');
db.save('exercise', {
    FullName: param_name, Age: param_age
}, function (err, res) {
    if (err) {
        // Handle error
        response += ' SAVE ERROR: Could not save record!!\n';
    } else {
        // Handle success
        response += ' SUCESSFUL SAVE: The record was saved in CouchDB!\n';
    }
    http_res.end(response);
});

this code works well and it saves the data to the CouchDB. My problem is when I want to read the data. The code that I wrote is:

  var cradle = require('cradle');
  var connection = new(cradle.Connection)('http://127.0.0.1', 5984, {
      auth: { username: 'toto_finish', password: 'password' }
  });

  var db = connection.database('test');
  db.view('exercise/all', {descending: true}, function(err, res)
  {
          console.log(res);
      res.forEach(function (row) {
          response = 'FullName: ' + row.FullName + '\n Age: ' + row.Age + '\n';
      });
  });
  http_res.end(response);

when I am trying to print response, response is empty and I don't know what I am doing wrong. I know that it does not go inside the forEach loop but I don't understand why.

the console output is:

[ { id: 'exercise',
    key: null,
    value:
     { _id: 'exercise',
       _rev: '1-7042e6f49a3156d2099e8ccb3cc7d937',
       FullName: 'Toto Finish',
       Age: '30' } } ]

Thanks in advance for any response or answer.

2 Answers2

0

Try moving the http_res.send() call inside the callback provided to db.view - the anonymous function( err, res ) { }.

I'm not sure however about the .forEach statement, you'll only get the last value from your query in the response variable, you should look into that as well.

spotirca
  • 471
  • 3
  • 3
0

spotirca is right

The db.view function is async so http_res.end(response) gets called before the view returns any data.

You can prove this by returning the date in both the console.log and http_res.end

console.log(res, new Date())

and

http_res.end(response, new Date());

The http response will have the earlier date/Time.

CRABOLO
  • 8,605
  • 39
  • 41
  • 68
Adam
  • 55
  • 6