I tried crud Operation using node js and mongodb.all crud operation working fine.but i tried to run get method its showing on;y one record.after i see my code its throwing error (Can't set headers after they are sent).How to solve this issue any one give suggestion.
index.js
router.get('/', async (req, res,next) => {
(async function() {
try {
await client.connect();
console.log("Connected correctly to server");
const db = client.db('olc_prod_db');
let r = await db.collection('Ecommerce').find();
r.forEach(function(result,err)
{
res.send(result)
})
// Close connection
client.close();
} catch(err) {
console.log(err.stack);
}
})();
});
router.get('/', async (req, res,next) => {
(async function() {
try {
await client.connect();
console.log("Connected correctly to server");
const db = db.collection('Ecommerce').find({}).toArray(function(error, documents) {
if (err) throw error;
res.send(documents);
});
} catch(err) {
console.log(err.stack);
}
})();
});
For each subsequent request, you have to 'send' once only. This method just completes the request cycle so you can't call it on loop because of loop run 'n' time.