0

Can anyone please explain why this:

// this works
router.route('/videos')
  .get((req, res)=>{
    Video.find()
      .exec()
      .then(console.log);
  });

// this also works
router.route('/videos')
  .get((req, res)=>{
    Video.find()
      .exec()
      .then(videos=>{
        res.json(videos)
      });
  });

works, and this:

router.route('/videos')
  .get((req, res)=>{
    Video.find()
      .exec()
      .then(res.json);
  });

doesn't?

The res object represents the HTTP response that an Express.js app sends when it gets an HTTP request. The console.log method outputs the videos data while res.json does not seem to be called.

Andrei Rosca
  • 1,097
  • 13
  • 27

1 Answers1

1

res.json does expect to be called as a method, with res being the this value. It works with console.log because that is already bound to the console object in node.

You can use

.then(res.json.bind(res))

or continue to use that arrow function. See also How to access the correct `this` context inside a callback?

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375