Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js: expressjs with mongoose

I'm working on my first node.js / express / mongoose app and I'm facing a problem due to asynchronisation mechanism of node.js. It seems I do not do the thing correctly...

Here is the test route I defined using express:

app.get('/test', function(req, res){
  var mod = mongoose.model('MyModel');
  mod.find({},function(err, records){
    records.forEach(function(record){
      console.log('Record found:' + record.id);
      // res.send('Thing retrieved:' + record.id);
    });
  });
});

When I issue a http://localhost/test, I'd like to get the list of records of type 'MyModel' in the response.

The code above is working fine but when it comes to returning this whole list to the client... it does not work (the commented res.send line) and only returned the first record.

I'm very new to node.js so I do not know if it's the good solution to embed several callback functions within the first callback function of app.get . How could I have the whole list returned ?

Any idea ?

like image 286
Luc Avatar asked Apr 09 '11 22:04

Luc


1 Answers

What you should be doing is:

mod.find({},function(err, records){
  res.writeHead(200, {'Content-Length': body.length});
  records.forEach(function(record){
    res.write('Thing retrieved:' + record.id);
  });
});

Please always check the documentation as well:

http://nodejs.org/docs/v0.3.8/api/http.html#response.write

I missed that you was using express, the send function is part of express and extend's the serverResponse object of node (my bad).

but my answer still applies, express's send function sends the data using ServerResponse.end() so there for the socket get's closed and you cannot send data any more, using the write function uses the native function.

You may also want to call res.end() when the request is fully completed as some item's within express may be affected

like image 88
RobertPitt Avatar answered Sep 19 '22 23:09

RobertPitt