Tips for locating documents by their ID within an array of IDs retrieved from a different schema

I am currently dealing with 2 mongoose Schemas structured like this:

 var RecipeSchema = new Schema({
      type: String,
      version: String,
      data:  [{type: Schema.ObjectId, ref: 'Data'}]
  });
  var Recipe = mongoose.model("Recipe", RecipeSchema);

 var DataSchema = new Schema({
     ex1: String,
     ex2: String,
     ex3: String
 });
 var Data = mongoose.model("Data", DataSchema);

If I have a "selected" recipe in a function, how can I use Data.find() to filter only the Data items with IDs matching those stored in the data array of the selected recipe?

Answer №1

When working with the chosen recipe called 'recipe', simply use the following code:

recipe.populate('data', function (error, populatedRecipe) {
    // The array of data objects will be stored in populatedRecipe.data instead of just _ids
  });

Please note that this method may not be effective if the selected recipe is lean or not a mongoose document.

Answer №2

Resolve field data type:

data: {
  type: [Schema.Types.ObjectId],
  ref: 'RecipeData',
  default: []
}

Example of Usage:

const Recipe = mongoose.model('Recipe');

router.get('/recipes', async (req, res) => {
  try {
    const recipesList = await Recipe.find({}).populate('data').lean();
    res.status(200).send(recipesList);
  }
  catch (error) {
    res.status(500).send({message: error.message});
  }
});

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

Failed to establish a connection with the Node.js server on the Raspberry Pi

I've been working on developing a nodejs app on my Raspberry Pi 2, but I've encountered an issue with connecting to the nodejs server. Every time I try to connect via localhost or remotely from my Mac (192.168.1.151:8080), I keep receiving the er ...

Encountering difficulties in installing firebase-tools via npm on MAC OSX 10.12.6 due to an error message stating "Unexpected end of JSON input while parsing near '...x","firebase":"~1.0.1)"

Currently, I am using node version 10.10.0 and npm version 6.4.1. I am attempting to install firebase CLI for a firebase project that has already been created in order to work on cloud functions. Strangely, the installation is successful on other systems ...

Starting up an express server with mocha testing

My express server throws an error when certain parameters are missing, such as the DB URI. I want to use Mocha to test this behavior, but I am not sure how to go about it. if(!parameters.db) { throw new Error('Please provide a db URI'); } I ...

The button in my form, created using React, continuously causes the page to refresh

I tried to create a chat application using node.js and react.js. However, I'm facing an issue where clicking the button on my page refreshes the entire page. As a beginner in web development, please forgive me if this is an obvious problem. You can fi ...

The Vue application is encountering an unexpected error in Chrome that is puzzling me as I search for a solution

Currently, I am delving deep into learning Vue.js and have decided to revisit the documentation from scratch and work through it in reverse order. Below is the content of my index.html file: <!DOCTYPE html> <html lang="en"> <hea ...

Error message in vuejs: JSON parsing error detected due to an unexpected "<" symbol at the beginning

I have been trying to troubleshoot this issue, but I am having trouble understanding how to resolve it. Currently, I am using lottie-web in a project and need to set the animation parameters on an object in order to pass them as a parameter later. This i ...

Organize mongoose models into groups according to the session variable

As I transition my application from MySQL to Node/Mongoose on Express, a new challenge arises. In my current LAMP stack, the "account_id" column is utilized in various tables to query based on the active account in the session. While replicating this logic ...

Retrieve the list of device tokens for the APNS service

Is it possible to retrieve a list of all device tokens on which my app is installed through an APNS endpoint? I am aware of the feedback service that provides the status of devices to whom messages are sent, but I believe this is only after the message ...

Display detailed information in InfoWindows when markers on a Vue Google Map are clicked

I'm working on creating a map similar to Airbnb's design. Each location marker displays the rental price, and when clicked, a popup with more details appears. However, I'm facing an issue where clicking any marker only shows the details of ...

Testing NestJS Global ModulesExplore how to efficiently use NestJS global

Is it possible to seamlessly include all @Global modules into a TestModule without the need to manually import them like in the main application? Until now, I've had to remember to add each global module to the list of imports for my test: await Tes ...

What is the correct method for routing Vue/AJAX requests in Laravel?

I am new to Laravel and creating a web service that can operate without the need for JavaScript, in case it is disabled by the user. However, I believe it would enhance the user experience if certain actions could be performed without having to refresh th ...

What is the significance of utilizing app.set() and app.get() in applications?

Is there a way to simplify this code: app.set('port', (process.env.PORT || 3000)); const server = app.listen(app.get('port'), () => { console.log('Server|Port: ', app.get('port')); }); Here is an alternative ...

Having trouble accessing datastore with node to retrieve data

I've been struggling with a simple get request built using node and express to fetch data from a datastore. The 'get' request seems to be stuck, and I can't seem to receive the results. I am unsure of what is causing this issue. const ...

Warning: Outdated version detected during NestJS installation on npm

Whenever I attempt to download NestJS using the command npm i -g @nestjs/cli, I encounter the following issue: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a6d5c9d3d4c5c3cb8ed7cbc1ccdcdffccdc3d0"><?[ ...

Using the for-each loop in Express.js with Node

I'm currently working on developing a REST API using express with Node. I have a requirement to iterate through a for loop in order to generate the desired JSON output. Here is a snippet of my route file: var Redis = require('ioredis') var ...

What is the best way to ensure reactivity in the Vue 2 Provide / Inject API?

After setting up my code in the following manner, I successfully managed to update checkout_info in App.vue using the setter in SomeComponent.vue. However, I noticed that the getter in SomeComponent.vue is not reactive. // App.vue export default { pr ...

To proceed with the aggregation operation in MongoDB, ensure that the argument passed is either a string containing 12 bytes or a string consisting of exactly 24 hex characters. Failure to meet

var objId=require('mongodb').ObjectId router.get('/view-ordered-products/:id',async(req,res)=>{ console.log(req.params.id) let orderedProducts=await userHelpers.findOrderedProducts(req.params.id) res.render('user/view-orde ...

When using Node Puppeteer, if the page.on( "request" ) event is triggered, it will throw an error message stating "Request is already being handled!"

I am currently utilizing puppeteer-extra in conjunction with node.js to navigate through multiple URLs. During each iteration, I am attempting to intercept certain types of resources to load and encountering the error below. PS C:\Users\someuser ...

Unraveling binary image data extracted from mongodb using node.js

My current project involves attempting to upload and retrieve images to and from MongoDB using Node.js and Mutter. I am encountering some challenges, especially when it comes to displaying the uploaded images in my .ejs file. Here is a snippet of my route ...

Encountering an error: TypeError - The class extending from an undefined value is not a valid constructor or null

I am currently working on developing a bot using the Microsoft Bot Framework that needs to be integrated with MS Teams. While trying to compile the code, I encountered an error stating "TypeError: Class extends value undefined is not a constructor or null. ...