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

Error Interceptor in AngularJS: Retrieving Current User Data from Backend

Seeking assistance with a function that retrieves the logged in user. I must confess that I obtained this code from a tutorial and do not fully comprehend its inner workings. After a period of inactivity (20 minutes), the token expires and invoking getCurr ...

What is the easiest way to clear browser cache automatically?

Hello, I have implemented an ajax auto complete function in one of my forms. However, I am facing an issue where over time, the suggestions get stored and the browser's suggestion list appears instead of the ajax auto complete list, making it difficul ...

An error occurs in TypeScript when attempting to reduce a loop on an array

My array consists of objects structured like this type AnyType = { name: 'A' | 'B' | 'C'; isAny:boolean; }; const myArray :AnyType[] =[ {name:'A',isAny:true}, {name:'B',isAny:false}, ] I am trying ...

What is the method for determining someone's age?

I am trying to extract the date from a field called "DatePicker" and then enter that date into the field labeled "NumericTextBox" Thank you <div> <sq8:DatePicker runat="server" ID="dateDatePicker"> <ClientEvents OnDateSelected="get_curr ...

Learn the connection and interaction dynamics among node.js, Angular, Express, and MongoDB

I'm currently delving into understanding communication within a MEAN stack. I've created the following code snippets by utilizing the Yeoman fullstack generator for scaffolding the application: Defined mongoose schema 'use strict'; ...

Managing spinners in Protractor when they are concealed by a wrapper element

While writing a test for an Angular app using Protractor, I encountered several issues with handling spinners. I managed to solve some of them, but I'm unsure how to test spinners that are hidden by a wrapper. For instance, when the parent tag has ng- ...

The Javascript executor in Selenium is delivering a null value

My JavaScript code is causing some issues when executed with Selenium's JavascriptExecutor. Strangely, the code returns null through Selenium but a value in Firefox developer console. function temp(){ var attribute = jQuery(jQuery("[name='q& ...

Detecting browser reload in React/Typescript: A guide

Is there a way to determine if the browser has been reloaded? I've explored various solutions, but most suggest using code like this: const typeOfNavigation = (performance.getEntriesByType("navigation")[0] as PerformanceNavigationTiming).type ...

Node.js is experiencing difficulties loading the localhost webpage without displaying any error messages

I am having trouble getting my localhost node.js server to load in any browser. There are no errors, just a buffering symbol on the screen. The code works fine in VS Code. Here is what I have: server.js code: const http = require("http"); const ...

Struggling with smoothly transitioning an image into view using CSS and JavaScript

I'm currently experimenting with creating a cool effect on my website where an image fades in and moves up as the user scrolls it into view. I've included the code I have so far below, but unfortunately, I keep getting a 404 error when trying to ...

Tips for including descriptions on individual images within the jQuery PhotoStack gallery

Recently, I encountered a challenge. I am currently utilizing a PHP file for accessing images stored in a specific folder. Here is the snippet of my PHP code: <?php $location = 'albums'; $album_name = $_GET['album_name']; $files ...

Having trouble retrieving XSRF-TOKEN from cookie in Next.js (React.js)?

When working with Next.js and Laravel 8 backend, I encountered an issue where I couldn't set the XSRF-TOKEN generated by Laravel on my fetch request for login. Despite being able to see the token in the inspect element > application tab > cookie ...

Ordering and displaying data with AngularJS

Trying to maintain a constant gap of 5 between pagination elements, regardless of the total length. For instance, with $scope.itemsPerPage = 5 and total object length of 20, we should have 4 pages in pagination. However, if $scope.itemsPerPage = 2 and tota ...

Infinity loop with AngularJS number input

I am facing an issue with a number input field where a function gets invoked whenever the number is increased or decreased: <input type="number" ng-model="amountOfInterval" ng-change="vm.changedAmountOfInterval(amountOfInterval)" /> However, this s ...

Using Jquery to handle input data in a form

Using jQuery, I have set up an AJAX function to fetch data from a database in real-time as the user fills out a form with 5 input fields. Currently, my code looks like this: $("#searchtype, #searchtext, #searchtag, #daterangefrom, #daterangeto").on("load ...

Using jQuery to toggle visibility on click within WordPress

Looking for a way to make three buttons change color on hover and display different content when clicked? You're not alone! Despite searching through tutorials and forums, the solution remains elusive. The buttons are structured like this: <div i ...

Facing an ESIDIR error in NextJs, despite the fact that the code was sourced from the official documentation

For an upcoming interview, I decided to dive into learning Next.js by following the tutorial provided on Next.js official website. Everything was going smoothly until I reached this particular section that focused on implementing getStaticProps. Followin ...

Issue with scrolling feature in div

I am currently facing an issue with scrolling on my website. Visit this site to see the problem. When scrolling down, it causes the "hidden" part of the site to slide up. I want to achieve a similar sliding effect, but it needs to be smooth. I have attempt ...

Establishing a connection to mongoHQ using mongojs hosted on heroku

I am currently attempting to establish a connection with mongoHQ from my node.js application. Below is the code snippet I have implemented: var databaseUrl = "mongodb://fishcuss:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail=" ...

Markers on Google Maps are failing to display when the locations are retrieved from a database

I am currently incorporating Google Maps API into my website using Node.js and mongodb. My Node.js express app fetches locations from mongodb, and I have successfully set up the map on my website. However, I am encountering an issue where only the hardcode ...