提问者:小点点

我使用nodejs和MongoDB尝试了crud操作。所有crud操作都正常工作。但是get方法只显示一个数据,而不显示所有数据


我尝试了使用节点js和Mongodb的crud操作。所有的crud操作都很好。但是我尝试了运行get方法,它只显示一个记录。我看到我的代码后,它抛出错误(不能设置标题后,他们被发送)。如何解决这个问题,大家给出建议。

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

  });

共2个答案

匿名用户

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

);

对于每个后续请求,您只能“发送”一次。此方法只是完成请求循环,因此您不能在循环时调用它,因为循环运行'n'时间。

匿名用户

中不需要,只需执行以下操作:

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