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

Fontawesome is unable to update the class due to the presence of invalid characters in the string

const toggleDarkOrLight = document.getElementsByTagName('i')[0]; var toggled = false; const toggleFunction = () => { if (toggled === false) { toggleDarkOrLight.classList.remove('fa fa-toggle-off'); toggleDarkOrLight.classLi ...

Is the user currently accessing the website in multiple tabs?

I am currently working on detecting the online status of users and need to update it when the tab is closed. The challenge I am facing is determining if the user has multiple tabs open so that the status remains the same, only updating when there are no ...

Guide to integrating a static page with personalized CSS and JavaScript resources within a Rails project

Currently, I am developing a simple Rails application (using Rails version 4.1) and I am looking to incorporate a static page into it. The static page is structured as follows: | |- index.html |- css folder |-- (various css files) |- js folder |-- (some j ...

Laravel does not have the capability to provide a genuine json response

I am facing an issue with my Laravel controller. The code is straightforward: class MyController extends Controller { public function list() { return response()->json(['a' => 'hello']); } } When I access the ...

Change the Bootstrap components according to the size of the screen

Is there a built-in Bootstrap feature to change an element's class based on screen size? I'm working on a webpage with scrollable card elements. On desktop, the cards are arranged horizontally, but on mobile they are stacked vertically, requirin ...

ejs scriptlet in ejs syntax (exclude)

My node version is v10.2.1, express version is 4.16.0, ejs version is 2.5.7. I would like to have the ability to modify the name of the layout in the future. Therefore, I set up my routing like this: router.get('/', function(req, res, next) { ...

Creating a visual representation from an array of strings to produce a

My goal is to organize a list of server names into a map using a specific logic. For instance, with names like: "temp-a-name1", "temp-a-name2", "temp-b-name1", "temp-b-name2" They would be mapped as: { a: [ "temp-a-name1", "temp-a-name2" ] ...

Exploring the power of ElasticSearch alongside Mysql

As I plan the development of my next app, I am faced with the decision between using NoSQL or a Relational Database. This app will be built using ReactJS and ExpressJS. The data structure includes relational elements like videos with tags and users who li ...

What is the process for transmitting images from React Native to native modules?

Challenge I am facing an issue trying to send an array of locally saved images from the JavaScript side (stored in an assets folder) to both iOS and Android native sides. The native code processes the images and returns a new image successfully when using ...

Locate a deeply nested element within an array of objects using a specific string identifier

Trying to search for an object in an array with a matching value as a string can be achieved with the following code snippet. Is there an alternative method to optimize this process without utilizing map? Code: const arr = [{ label: 'A', ...

Errors that occur during Javascript runtime in the Express framework

I'm currently working on an Express app with several routes. One of them looks like this: router.post('/upload', (req, res) => { let audioFile = req.files.audioFile; const file = __dirname + '/../' + req.body.uploadLocation ...

HTML dropdown menu to trigger an action with the submitted URL

I need assistance creating a menu of options with corresponding URL actions. Here is the structure I have in mind: <form> <select> <option value="1">1</option> <option value="2">2</option> <option value="3 ...

How can I initiate an AJAX POST request over HTTPS?

Despite my efforts, I am consistently encountering a 404 error when attempting to make an Ajax POST request. The specific error message reads: "GET 404 (Not Found)." Could this issue be related to the site's use of https? Below is the code snippet t ...

What is the significance of authors stating "AngularJS compiles the DOM"?

Currently, I am diving into the book Lukas Ruebbelke's AngularJS in Action, The author emphasizes throughout the text that, In AngularJS, a view is essentially the modified version of HTML after it has been processed by AngularJS. I'm struggli ...

When using Rspec and Capybara, utilizing jQuery to set focus on an element may not apply the `:focus` CSS as expected

I have implemented jump links for blind and keyboard users on my website, but I've hidden them off-screen visually. When these links gain focus, they are moved into the viewport. Trying to test this behavior using RSpec and Capybara has been unsucces ...

Interested in discovering the ins and outs of the JavaScript Map function?

Currently, I am delving into this JavaScript function: function solution (array, commands) { return commands.map (v => { return array.slice(v[0] -1, v[1]).sort((a, b) => a - b).slice(v[2] -1, v[2])[0]; }); } I am puzzled about th ...

I desire to incorporate a subtle fading effect into the script

I have written the script code and now I am looking to add a fade effect to it. Can anyone guide me on how to achieve this? Your help is much appreciated! ※I used an online translator as English is not my native language. Please bear with any awkward ph ...

Converting UK DateTime to GMT time using Angular

I am currently working on an angular project that involves displaying the start and end times of office hours in a table. For instance, the office operates from 8:30 AM to 5:30 PM. This particular office has branches located in the UK and India. Since u ...

Error: Property 'onclick' cannot be set on a null object

JavaScript isn't my strong suit, so I'm struggling to solve this issue. The console is showing me the following error message: Uncaught TypeError: Cannot set property 'onclick' of null <script> var modal = document.getE ...

Typescript polymorphism allows for the ability to create various

Take a look at the following code snippet: class Salutation { message: string; constructor(text: string) { this.message = text; } greet() { return "Bonjour, " + this.message; } } class Greetings extends Salutation { ...