Retrieving information from MongoDB for a specific ObjectID associated with the current authenticated user

Having two collections in my MongoDB structured as follows:

Data

User:

id: ObjectId ("5fb39e3d11eaad3e30cfb1b0")
userName: "Tobias"
password: "yyy"

id: ObjectId ("5fb3c83fb774ff3340482250")
userName: "Thor"
password: "xxx"

Courses:

id: ObjectId ("5fb3cf3da8227e101826e2db")
CourseName: "Design"
userId: "5fb39e3d11eaad3e30cfb1b0" (THIS IS THE SAME AS THE OBJECT ID FOR THE FIRST USER) 

When a user logs in, they can add a course which then gets added to the MongoDB collection along with the coursename.

I'm trying to figure out how to display only the courses that match the currently logged in user. My tech stack includes Mongoose for user-login, Express for server connection, EJS for view, and VueJS for control.

Coming from relational databases, I'm unsure if my approach of joining objectIDs is a good practice or not.

Answer №1

If you're working with MySQL, you'll be familiar with joining tables. However, in MongoDB, the equivalent operation involves using $lookup

   BooksModel.aggregate([
      {
        $lookup: {
          from: AuthorModel.collection.name,
          localField: "authorId",
          foreignField: "_id",
          as: "author"
        }
      },
    ]).then(res => {
       console.log(res);
    })

The resulting data will include an additional field called author, which will contain an array of documents that match the authorId

While you can specify a string instead of AuthorModel.collection.name, it's recommended to dynamically determine the collection name.

Answer №2

To search for a specific item, you have the option to utilize either the find() or findOne() method.

courses.findOne(function (err, course) {
  if (err) return handleError(err);
  if (course) {
    // Perform action
  }
});

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

Implement the callback-console.log feature from the epic-games-api into an Express.js application

Looking to integrate Epic Games output into an Express.js GET request but don't have any JavaScript experience, so go easy on me! XD const EpicGamesAPI = require('epicgames-status'); const express = require('express') const app = ...

What is the process for incorporating custom controls into the Mantine Embla Carousel within a Next.js environment?

Check out this code snippet: import React from "react"; import { Container } from "@mantine/core"; import { Carousel } from "@mantine/carousel"; import { ArticleCard } from "@/components"; import { cards } from " ...

I'm unable to resolve all parameters for xxx -- unit testing using jest

I recently encountered an issue with a test in jest that is failing and displaying the following error message: Error: Can't resolve all parameters for LoginService: (?). at syntaxError (/Users/wilson.gonzalez/Desktop/proyecto_andes/external/npm/nod ...

What could be the reason for receiving a 431 status error after including a JWT token in the Authorization section of the header?

Currently, I am in the process of developing a full stack React application with Express and Node. I have successfully integrated auth0 for authentication and authorization purposes. However, I have encountered an issue and am seeking suggestions on how to ...

Tips for creating a personalized asynchronous Express handler that seamlessly receives specific typed parameters

In my quest to create a unique Express endpoint wrapper, I aim to wrap async functions and handle errors effectively. The current implementation is basic but functional: import type {Request, RequestHandler, Response} from 'express'; type Handle ...

Using CSS properties as false values within React applications

Can you provide guidance on using conditional styles with conditional operators? What would be the ideal code example? Is it possible to use non-CSS values? margin: isOpen ? '10px' : undefined margin: isOpen ? '10px' : 'initial&a ...

How can you gradually fade out the bottom edge of a rendered component until it is re-rendered?

Currently, I am developing a reviews microservice for an e-commerce platform using react and react-bootstrap. My goal is to showcase 5 reviews initially, followed by a button to expand and reveal more reviews. In order to achieve this, I envision the botto ...

Verify whether the user's email is registered in the database

I have a login form and I want to verify if a user's email exists in the database, but I'm not sure about the syntax for integrating Angular with Node. In my Main.js file, I have an ng-click on the submit button that triggers this function. I ex ...

Does the TS keyof typeof <Object> rule prohibit the assignment of object.keys(<Object>)?

I'm having trouble understanding the issue with this code snippet. Here is the piece of code in question: export type SportsTypes = keyof typeof SportsIcons export const sports: SportsTypes[] = Object.keys(SportsIcons); The problem arises when I at ...

Making a Button-triggered Post Request in NodeJS

I am unsure if this is achievable, but after conducting research, it seems that using a form and text input can make it possible. My goal with NodeJs & Express is to have the ability to send a post request to my Node.JS server when a button on my webpage i ...

Exploring the Power of v-for in Nested Objects with Vue

I currently have a dataset in the following structure: itemlist : { "dates": [ "2019-03-15", "2019-04-01", "2019-05-15" ], "id": [ "arn21", "3sa4a", "wqa99" ], "price": [ 22, 10, 31 ] } My goal is t ...

Tips for closing print window dialog during Protractor testing

Currently, I am performing end-to-end testing using protractor. During a specific test, I need to verify if the print button is successfully creating a PDF. When the test clicks on the button, it triggers a print window dialog as shown below: https://i.st ...

Navigating a JSON array using the Handlebars template engine

I have a JSON file and I am looking for guidance on how to display the information from it using the handlebars template engine: This is the template code: <script id="template-app" type="text/x-handlebars-template"> {{#each data}} Emai ...

Having trouble with installing node-steam on your node.js server?

I recently attempted to install node-steam and encountered a significant error. Can anyone provide guidance on how to resolve this issue? Is the mistake on my end? ... gyp ERR! configure error gyp ERR! stack Error: Can't find Python ex ...

How can I resolve the issue of encountering the "Modal dialog present: If you navigate away from this page, any unsaved changes will be lost" message while using Internet Explorer with

Here's the code snippet I'm working with. While it successfully removes the alert box, it throws an error in the console: Exception in thread "main" org.openqa.selenium.UnhandledAlertException: Modal dialog present: If you leave this page, any c ...

Infinite scroll causing Firebase ".length" function malfunction

My NextJs website is encountering errors related to Firebase infinite scroll. The issue seems to be with the .length property being undefined for some unknown reason. I am struggling to debug the code and make it work properly in Next.js. Any help would be ...

Can someone help me figure out how to increase the values of two specific attributes within a class?

Currently facing a challenge with adjusting the number of likes and comments using increment for properties 'numberOfLikes' and 'comments'. Unsure whether to utilize a for loop or just the increment operator. Still new to coding, so apo ...

Adding client-side scripts to a web page in a Node.js environment

Currently, I am embarking on a project involving ts, node, and express. My primary query is whether there exists a method to incorporate typescript files into HTML/ejs that can be executed on the client side (allowing access to document e.t.c., similar to ...

The jQuery .hasClass() function does not work properly with SVG elements

I am working with a group of SVG elements that are assigned the classes node and link. My goal is to determine whether an element contains either the node or link class when hovering over any of the SVG components. However, I am encountering an issue where ...

Strange CSS/browser storage glitch

UPDATE: JUST REALIZED THIS ISSUE IS ONLY OCCURRING ON FIREFOX, NOT CHROME ANOTHER UPDATE: Oddly enough, this problem only occurs locally. When I push it to GitHub, everything works fine. So strange. I suppose that means it's not a major issue. On my ...