Retrieve all documents with a matching objectId field in MongoDB

I built an API that can fetch all data from a table, but within this table there is an object ID reference to a user.

Table 1 - Story | Table 2 - User

api.get('/all_stories', function(req, res) {
    Story.find({}, function(err, stories) {
        if (err) {
            res.send(err);
            return;
        }
        res.json(stories);
    });
});

This API retrieves all the data within the Story table and returns it as JSON.

creator: { type: Schema.Types.ObjectId, ref: 'User' },
content: String,
created: { type: Date, default: Date.now() }

How can I use ref: 'User' to find and display other data columns inside the User table? Or maybe even return it as JSON?

Answer №1

To accomplish this task, you will need to utilize the populate method.

Click here for more information on how to use populate in Mongoose

Story
.find({})
.populate('creator')
.exec(function (err, stories) {
        if (err) {
            res.send(err);
            return;
        }
        // The 'stories' variable now holds an array of Story objects, with their creator property populated with user documents
        res.json(stories);
})

It appears that your model structure is very similar to the one shown in the documentation example...

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

Tips for passing a function and an object to a functional component in React

I am struggling with TypeScript and React, so please provide clear instructions. Thank you in advance for your help! My current challenge involves passing both a function and an object to a component. Let's take a look at my component called WordIte ...

Save various checkbox options to firebase

Utilizing Angularfire, my goal is to save data using multiple checkboxes. HTML <form role="form" ng-submit="addTask(task)"> <label class="checkbox-inline" ng-repeat="(key, value) in students"> <input type="checkbox" id="{{key}}" valu ...

<use> - SVG: Circles with different stroke properties

Why is the stroke of both <use> elements being ignored here? The stroke color of <circle> is set to blue, which is also appearing on both <use> elements. Why? I am trying to set different stroke colors for all three of these elements, bu ...

Looking for an easy solution in RegExp - how to locate the keys?

Similar Inquiries: Retrieving query string values using JavaScript Utilizing URL parameters in Javascript I am tasked with extracting specific keys from a series of URLs where the key is denoted by 'KEY=123'. My goal is to identify and e ...

Searching for an array of IDs in Mongoose

I have created an API using Express.js and mongoose to find users based on their ids in an array. // Here is the array of user ids const followedIds = follow.map((f) => f.followed); console.log(followedIds); // This will log [ '5ebaf673991fc60204 ...

Bootstrap typehead not activating jQuery AJAX request

I am attempting to create a Twitter Bootstrap typehead using Ajax, but nothing seems to be happening. There are no errors and no output being generated. Here is the jQuery Ajax code I have implemented: function CallData() { $('input.typeahea ...

Having Trouble Adding Details to a New Cart for a User in Angular and MongoDB - What's Going On?

After working on an E-Commerce site for a while, I hit a roadblock. Despite taking a break and coming back with determination, I can't seem to resolve the issue at hand. The application features registration, login, product search, and a popup window ...

Looking to create a format for displaying short comic strips in a grid pattern

I am struggling to create an image grid for my small comics. I want to have 2 columns and 3 rows, but all the divs end up in the same place. I tried using display: flex, but it didn't work as expected. Additionally, I want the grid to be responsive, b ...

Ways to retrieve all elements based on their class names?

What is the equivalent of using $('.class') in JQuery to get all elements by class name with pure JavaScript? ...

When attempting to send an array value in JavaScript, it may mistakenly display as "[object Object]"

I queried the database to count the number of results and saved it as 'TotalItems'. mysql_crawl.query('SELECT COUNT(*) FROM `catalogsearch_fulltext` WHERE MATCH(data_index) AGAINST("'+n+'")', function(error, count) { var ...

Creating an AngularJS factory that integrates with a Parse.com database

Hey there, I've been diving into AngularJS factories to manage data outside of controllers but I'm hitting a roadblock. I could really use some guidance, advice, or direction on this issue. Here's what I have so far, but I'm struggling ...

Using Javascript's OnChange event to dynamically update data

Attempting to achieve a seemingly straightforward task, but encountering obstacles. The goal is to trigger a JavaScript onChange command and instantly update a radar chart when a numerical value in a form is altered. While the initial values are successful ...

Encountered issue while converting half of the string array to JSON using JavaScript

I encountered an issue with the code below while trying to convert an array into JSON. Here is my code: <html> <head> </head> <body style="text-align:center;" id="body"> <p id="GFG_UP1" style="font-size: 16px;"> </p ...

Show/Hide a row in a table with a text input based on the selected dropdown choice using Javascript

Can someone please assist me with this issue? When I choose Business/Corporate from the dropdown menu, the table row becomes visible as expected. However, when I switch back to Residential/Consumer, the row does not hide. My goal is to only display the row ...

What is the best way to access and manipulate data stored in a Firestore map using React?

In my Firestore database, I have a field with map-like data: coordinates:{_01:"copper",_02:"gold",_03:"iron"} When viewing this database in the Firestore admin panel, it appears like this: pic However, when attempting to list items using the following c ...

How to include a key-value pair to a JSON object within an array using JavaScript

I am looking to include the following functionality in the JSON data provided below: "Check if the key name default exists, and if it does, add another key within the same object => ("pin" : 91)." I have attempted to achieve this using the code snippet b ...

Error parsing data in the $.ajaxSetup() function of JQuery

Currently, I am coding a program using jQuery. It was functioning perfectly in Firefox 3.5 until I upgraded to Firefox 4.0. Since then, the dreaded 'parsererror' keeps popping up and causing me quite a headache. I've pinpointed the exact pa ...

Is there a way to download and store the PDF file created using html2pdf in Node.js on my local machine?

I have successfully generated a PDF using html2pdf, but now I want to either send it to my server in Node.js or save it directly onto the server. Currently, the PDF is downloaded at the client's specified path, but I also need a copy saved on my serve ...

module 'next/router' cannot be located or its associated type declarations are missing

Running into some issues with my NextJS application. An unusual error message is appearing, even though my code is functioning smoothly without any errors. import { useRouter } from 'next/router'; // Cannot find module 'next/router' or ...

Determine the total number of arrays present in the JSON data

I'm currently working on a straightforward AngularJS project, and here's the code I have so far: This is my view: <tr ng-repeat="metering in meterings"> <td>1</td> <td>{{metering.d.SerialNumber}}</td> ...