开发者

node.js: expressjs with mongoose

开发者 https://www.devze.com 2023-02-23 01:35 出处:网络
I\'m开发者_JS百科 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...

I'm开发者_JS百科 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 ?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号