I tried crud operation using nodejs and mongodb. all crud operation is working fine.but get method showing only one data not showing all data

纵饮孤独 提交于 2019-12-14 04:12:01

问题


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);
        }
      })();

  });

回答1:


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.




回答2:


No need in forEach, just do:

const r = await db.collection('Ecommerce').find({}).toArray();
res.send({ data: r })


来源:https://stackoverflow.com/questions/55812098/i-tried-crud-operation-using-nodejs-and-mongodb-all-crud-operation-is-working-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!