Node.js: expressjs with mongoose

I am working on my first node.js / express / mongoose application and I ran into a problem due to the node.js asynchronization mechanism. It seems I am not doing it right ...

Here is a test route that I defined using an expression:

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 exit http: // localhost / test , I would like to get a list of records like "MyModel" in the response.

The code above works fine, but when it comes to returning all this list to the client ... it does not work (comment line res.send) and returns only the first record.

I am very new to node.js, so I don’t know if this is a good solution to embed multiple callback functions in the first app.get callback function. How could I return the whole list?

Any idea?

+6
source share
1 answer

What you should do:

 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:

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

I missed that you used express, the submit function is part of the expression and extends the serverResponse node object (my bad).

but my answer is still applied, the express send function sends data using ServerResponse.end() , so where the socket is closed and you cannot send data anymore using the write function, it uses the built-in function.

You can also call res.end() when the request is completely completed, as some element within the express function may suffer

+9
source

Source: https://habr.com/ru/post/885582/


All Articles