The Covenant of Contracts in mongoose

I'm curious as to why the following code snippets behave differently:

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

and why this doesn't work:

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

I am trying to understand why one piece of code outputs data using console.log, while another piece does not seem to call res.json.

Answer №1

When using the res.json method, it is important to make sure that it is called as a method with the right context. In this case, <code>res
should be passed in as the this value. This is why it works correctly with console.log, as it is already bound to the console object in node.

If you want to ensure that the correct context is maintained when using .then, you can use:

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

Alternatively, you can continue using an arrow function. For more information on accessing the correct `this` context inside a callback, refer to How to access the correct `this` context inside a callback?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to merge two variables together and receiving this error message: "mergedObject is not defined."

New to Node.js/Express and trying to combine two objects to save them to a collection. Any advice would be greatly appreciated! Thank you in advance for your time. This is what I've put together, but it's not functioning as expected: app.post( ...

What is the best way to use hasClass in a conditional statement to display text based on the content of a different div element?

Let's say we have the following HTML code: <div>New York</div> Now, we want to add another div like this: <div>Free Delivery</div> How can we achieve this using JavaScript? ...

Could it be a potential issue with array sorting in Chrome and IE?

My array sorting script works perfectly on Firefox, however, Chrome and IE are giving me an unordered array. var arr = ["2017-02-17", "2017-02-17", "2017-02-16", "2017-02-15", "2017-02-16", "2017-02-15", "2017-02-14", "2017-02-16", "2017-02-17", "2017-02- ...

Executing functions in AJAX using JavaScript callbacks

I'm in need of assistance to grasp how to start working on this problem. I have a task to write code for an object that allows multiple functions to be registered to execute a single common callback function. The objective of the object is to run al ...

JavaScript string representing the actual value of a string

In order to reliably extract string literals from a JavaScript string, I need to create a function, let's name it f. Here are some examples: f('hello world') //-> 'hello world' (or "hello world") f('hello "world"') / ...

Alter the app's entire background color in React.js with a button click

I am facing an issue with changing the background color of my entire React App when a button is clicked. Currently, I am able to change the color of the button itself but not the background. I have imported the App.css file into my project and I am looking ...

Having trouble resizing a KineticJs group to 300x300?

Attempting to adjust the size of a kinetic group is resulting in an error message in JavaScript. The Kinetic JS documentation states that setSize should work with group nodes. ...

The functionality of getAttribute has changed in Firefox 3.5 and IE8, no longer behaving as it did before

Creating a JavaScript function to locate an anchor in a page (specifically with, not an id) and then going through its parent elements until finding one that contains a specified class. The code below works perfectly in Firefox 3.0 but encounters issues wi ...

Substitute all numerical values with a designated number from a variable

I came across a link that looks like this foo.net/index.php?page=15 My goal is to replace any number after page=xxx and retrieve the new number from a variable Currently, my code only replaces 15 with 16 var num = 16, // What if the str = foo.net/index ...

Tips for updating the corresponding nav link in CSS when transitioning between pages

In order to highlight the current page in the navigation menu, one method is to use an active attribute on the nav-link of the respective page: <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link navLink ...

Issues encountered during the deployment process on Vercel

I've encountered an issue while deploying my Next.js app on Vercel. It seems to be related to an unsupported platform error. I have attached an image displaying the exact error message. npm ERR! code EBADPLATFORM npm ERR! notsup Unsupported platform f ...

Using Ajax to pass a dictionary of dictionaries

I'm currently developing a Django website and facing an issue with passing data from Javascript to Python using Ajax. Below is the code snippet: // Javascript file function myFunc() { {...} // Generate var 'values' which is a di ...

Styling for Ajax Forms when traditional methods don't work

I'm working on an Ajax form and I want to ensure there's a solid fallback in case the user has JavaScript disabled. Currently, the form functions without JavaScript, but the user sees the JSON string displayed as plain text without any styling du ...

Nextjs attempting to access local storage without proper initialization

I'm currently working on a feature where I have a sidebar with two buttons, contact and profile. When a user clicks on either of them, the URL updates to: /?section=clickedItem, allowing the user to save the state and return to that specific page upon ...

Tips for efficiently storing large Twitter profile ids in a Node JS application

I am encountering an issue while trying to store the followers of a few users on Twitter. The followers/ids endpoint provides a list of IDs, but not in the id_str format. I have been attempting to convert these IDs into string format, but when I use large ...

Avoid commencing an EmberJs application with static assets already in place

Is there a way to obtain the minified EmberJs JavaScript and CSS assets without automatically initializing the EmberJs App? The scenario is having a login.html where users can log in, but with the static assets preloaded to eliminate waiting time once red ...

Adjust the color of radio button text with Jquery

Here is a sample of radio buttons: <input type='radio' name='ans' value='0'> Apple <input type='radio' name='ans' value='1'> Banana <input type='radio' name='ans&apo ...

What is the best way to manage classNames dynamically in React with Material-UI?

I am wondering how to dynamically add and remove classes from an img tag. My goal is to change the image automatically every 2 seconds, similar to Instagram's signup page. I am struggling to achieve this using the material-ui approach. Below is a snip ...

What are some ways to include additional data besides the new value in a change event for an input field?

Currently, I am using VueJS to dynamically generate a form based on a JSON schema and then attempting to save the data into my Vuex state. Here is an overview of the code I have written so far (simplified): <div v-for="field in schema" :key=& ...

What is the best way to display information in a Handlebars template file?

Having trouble displaying data in the template using NestJS with mysql. Here is the code snippet from controller.ts: import { Controller, Get, Post, Put, Delete, Body, Param, Render, UsePipes, Logger, UseGuards} from '@nestjs/common'; import { P ...