Is there a method to retrieve the IDs of two distinct collections within a single JavaScript function?

I am dealing with two collections within a single database – "Neighborhood" and "Restaurants". My goal is to identify the exact neighborhood I am currently in so that when I click on the "back" button located on the restaurant.ejs page, it directs me back to the page associated with that specific neighborhood's id.

Despite my attempts using findById({} ... and findById(id, ..., I have been encountering errors.

Below is my code snippet. Could you assist me in determining what should be added in place of the ??? for a potential resolution?

neighborhood.get('restaurant/:id', (req, res) => {
  Restaurant.findById(req.params.id, (err, restaurantInfo) => {
    Neighborhood.findById(???, (err, foundNeighborhood) => {
      res.render('restaurant.ejs', {
        restaurant: restaurantInfo,
        neighborhood: foundNeighborhood
      })
    });
  });
});

Answer №1

Assuming I've comprehended your query correctly, the information returned by restaurantInfo will either include details about the neighborhood as mentioned by @paolo, or you may need to establish a method to search for the neighborhood within the req, perhaps in this manner:

 Restaurant.findById(req.params.id, (err, restaurantInfo) => {
    Neighborhood.findById(req.params.neignborhoodId, (err, foundNeighborhood) => {
      res.render('restaurant.ejs', {
        restaurant: restaurantInfo,
        neighborhood: foundNeighborhood
      })
    })
  })
});

If there are errors occurring, it's advisable to incorporate error checking in the callback function like so:

 Restaurant.findById(req.params.id, (err, restaurantInfo) => {
   if (err) {
     return err  // additional error message can be added here
   } else {
    Neighborhood.findById(req.params.neignborhoodId, (err, foundNeighborhood) => {
      if (err) {
        return err
      }
      res.render('restaurant.ejs', {
        restaurant: restaurantInfo,
        neighborhood: foundNeighborhood
        }
      })
    })
  })
});

In my opinion, depending on your project requirements, it might be simplest to include the neighborhood id as part of the restaurant information. In that case, you could pass in the neighborhood id like this:

Neighborhood.findById(restaurantInfo.neighborhoodId, (err, foundNeighborhood) => {

If feasible, utilizing the neighborhood name to locate the neighborhood id could be an option since you specified that the restaurantInfo includes the neighborhood name. Alternatively, you could opt for a Neighborhood.findByName search instead of using findById.

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

Checking Sudoku Solutions on Codewars

I have come across this JavaScript code which seems to be functioning correctly. However, I am curious about the line board[3][8] != board[8][3] and how it checks for repeating row and column numbers. Can someone please provide an explanation? Thank you! ...

Creating a circular frame for your image to use as a Facebook profile picture

In the process of developing an input feature that allows users to upload file images for avatar changes, similar to Facebook's functionality. However, I am aware that Facebook utilizes a circular area for avatars and enables users to adjust the image ...

Launch in a new window using JavaScript

Check out my interactive map here. Currently, when I click on different sections of the map, the target page opens in the same window. However, I would like it to open in a new window instead. <iframe src="http://bluewingholidays.com/map/map.html ...

Use Angular2 to showcase the selected image as the main one when the user clicks on the

I'm working on creating a product thumbnail gallery, and I'd like the main image to be displayed when the user clicks on a thumbnail. I am using Angular for this project, although I am still learning my way around the framework. product.html &l ...

What is causing my props to return the index along with its value?

My variable named "subject" holds the string "Test". I am passing it to a props child using the following method: onRowSelect(slotProps) { this.subject = { ...slotProps.data.subject.split() }; } Upon receiving the value of "subject" in my compo ...

What sets apart `ng-if` from `data-ng-if`?

Can you explain the distinction between ng-if and data-ng-if? Although they appear to function similarly, I'm struggling to discern the specific difference as there isn't much information out there on data-ng-if. ...

I am seeking to enable a specific div when the crawler condition is met

This specific div houses the character and becomes active when the character is clicked. Upon clicking, a jQuery function is triggered to display other countries. //this particular div should remain active when the crawler condition is met. It displays th ...

How to correctly utilize Mongoose's findOneAndUpdate method

Currently, I am learning Node.js with Express and Mongoose by myself. The section of the website that I'm focusing on is a polling system. Everything is working smoothly except for one crucial part – tracking user votes... In my poll handler, this ...

Steps for adding a border to kendo grid row hover

One of my tasks involved creating a grid using Kendo, and I wanted to display borders on a grid row when the cursor hovers over it. I attempted the following code snippet: .k-grid > table > tbody > tr:hover, .k-grid-content > table > tbody ...

Display a hoverable button for a singular element within an array during the process of mapping through the array

const ChatWidget = () => { const bodyRef = useRef(null) const [{messages,roomMessages,roomID,socket,user}, dispatch] = useStateValue() const [dropdown, setDropdown] = useState(false) useEffect(()=>{ const setScreen = () =>{ bodyRef.cur ...

What exactly does the context parameter represent in the createEmbeddedView() method in Angular?

I am curious about the role of the context parameter in the createEmbeddedView() method within Angular. The official Angular documentation does not provide clear information on this aspect. For instance, I came across a piece of code where the developer i ...

The onClick() function in JavaScript is encountering issues on the Firefox OS mobile application

I've been working on an app for Firefox OS mobile devices where I'm trying to trigger a Javascript function onClick() from a div attribute. It's functioning properly in regular browsers, but when I test it in the simulator, the onClick funct ...

Querying a Mongoose database using ObjectID references

I am working with two schemas: let adSchema = mongoose.Schema ( { author: {type: ObjectId, ref: 'User'}, title: {type: String, required: true }, town: {type: ObjectId, ref: 'Town', required: true}, } ...

Can a model be embedded_in what it embeds as embeds_one in Mongoid?

Can a relationship like the one below be established: User: class User include Mongoid::Document include Mongoid::Paperclip include Mongoid::Timestamps store_in :users belongs_to :team field :full_name, :type => String field :email, ...

Storing Previous Commands in NodeJS ssh2

In my current project, I am utilizing the ssh2 library in conjunction with express js. The flow involves the client sending a POST request to the express api, which triggers the creation of a file. Subsequently, ssh2 is used to transfer the file from one d ...

Running complex operations within a sorting function just once

I am facing the challenge of sorting an array of objects based on multiple date fields, with the added complexity of excluding certain dates depending on the category. In order to optimize performance, I want to minimize the number of times the getUsefulJo ...

Encountered an unexpected issue: Attempting to convert a circular structure to JSON. Can you identify the root cause of

There seems to be an error with the form submission: The form is not updating in the database. The following error is being displayed. const handleAddItem = (event) => { event.preventDefault(); const productName = productNameRef.current.value; ...

Tips for handling a JSON payload retrieved through a POST request

I'm currently working on a button that triggers a POST call to retrieve a json response from the server. My goal is to display this json response in a new (chrome) browser tab. Here's what I have so far using Angular: $http.post(url, data) .t ...

Next JS encountered an error - Error [ERR_HTTP_HEADERS_SENT]: It is not possible to set headers after they have already been sent to the

Having crafted a serverless application using next.js, Vercel, and Google Sheets to store customer contact data, I encountered an issue post-deployment. While my application works flawlessly locally, after deployment, I started receiving the following erro ...

Requesting data from an external URL using Ajax

Attempting to retrieve specific data attributes from my personal Duolingo account has led me to encounter a JSON object upon entering the following URL: (substituting "username" as my id in the url). var getDuolingoData = function() { return $.ajax( ...