Mongoose: The aggregate method does not filter properly when using Model.field_1.field_2

Explaining a custom function:

const getNotificationsForLounge = async (lounge_id) => {
  try {
    const notifications = await Notification.aggregate([
      {
        $match: {
          "lounge_join_request.lounge": lounge_id,
          lounge_join_request: { $ne: null },
        },
      },
    ]);
    console.log("🚀 ~ notifications:", notifications);
    // Process notifications
    return notifications;
  } catch (error) {
    console.log("🚀 ~ error:", error);
    // Handle errors
  }
};

The above function takes a lounge_id and retrieves notifications where

notification.lounge_join_request.lounge
matches the given lounge_id.

I also created another function that selects a random notification, extracts its lounge_join_request.lounge_id, and passes it to the first function.

const getNotificationWithRandomLoungeJoinRequest = async () => {
  try {
    const notification = await Notification.aggregate([
      {
        $match: {
          category: "LOUNGE_JOIN_REQUEST",
          lounge_join_request: { $ne: null },
        },
      },
      { $sample: { size: 1 } },
      {
        $lookup: {
          from: "lounge_join_requests",
          localField: "lounge_join_request",
          foreignField: "_id",
          as: "lounge_join_request",
        },
      },
      { $project: { _id: 0, lounge_id: "$lounge_join_request.lounge" } },
    ]);
    const lounge_id = notification[0].lounge_id[0];
    console.log(
      "🚀 ~ file: loungeServices.js:663 ~ getNotificationWithRandomLoungeJoinRequest ~ lounge_id:",
      lounge_id
    );
    // When passing this lounge_id to the previous function,
    // It returns an empty array instead of expected results
    return await getNotificationsForLounge(lounge_id);
  } catch (error) {
    console.log("🚀 ~ error:", error);
  }
};

Even though I take lounge_id from an existing notification, the first function should at least display that specific notification. However, it always returns an empty array. Highlighted here:

 const lounge_id = notification[0].lounge_id[0];
    // Logs a lounge id
    // 🚀 ~ file: loungeServices.js:663 ~ getNotificationWithRandomLoungeJoinRequest ~ lounge_id: 63ef344xxxxb4943355
    // Which means there exists a notification
    // Where notification.lounge_join_request.lounge equals this lounge_id
    console.log(
      "🚀 ~ file: loungeServices.js:663 ~ getNotificationWithRandomLoungeJoinRequest ~ lounge_id:",
      lounge_id
    );

    // But, when I feed that lounge_id into this function
    // Which searchs notifications where
    // notification.lounge_join_request.lounge equals this lounge_id
    // It logs an empty array
    return await getNotificationsForLounge(lounge_id);

Any thoughts on why?


Models related to this scenario:

Notification.js

const NotificationSchema = new Schema({
  lounge_join_request: {
    type: Schema.Types.ObjectId,
    ref: "lounge_join_requests",
    default: null,
  },
});

module.exports = Notification = mongoose.model(
  "notification",
  NotificationSchema
);

LoungeJoinRequest.js

const LoungeJoinRequestSchema = new Schema({
  lounge: {
    type: Schema.Types.ObjectId,
    ref: "lounge",
    required: true,
  },
});

module.exports = LoungeJoinRequest = mongoose.model(
  "lounge_join_requests",
  LoungeJoinRequestSchema
);

Lounge.js

const LoungeSchema = new Schema(
  {
    name: {
      type: String,
    },
  }
);

module.exports = Channel = mongoose.model("lounge", LoungeSchema);

Answer â„–1

In your database structure, the lounge_join_request field stores an ObjectId instead of an actual object. Therefore, there is no lounge_join_request.lounge field available for comparison.

If the lounge_id value matches the _id of the lounge join request document, you can create a match using:

 {
     $match: {
        lounge_join_request: lounge_id,
        lounge_join_request: { $ne: null },
     },
 }

Answer â„–2

The issue you mentioned might not actually be a problem. The first aggregation should return a result if the lounge attribute is set in the lounge_join_requests collection. You can verify this by checking out this Mongo Playground Snippet

The actual issue could be with your getNotificationsForLounge method. It seems like you are attempting to retrieve notifications using the lounge_id, which corresponds to the lounge collection, not the notification collection. Therefore, querying by lounge_id from the lounge collection won't yield any useful results.

If you still need to accomplish this, consider updating your getNotificationsForLounge method as follows:

const getNotificationsForLounge = async (lounge_id) => {
  try {
    const notifications = await Notification.aggregate([
      {
        $lookup: {
          from: "lounge_join_requests",
          localField: "lounge_join_request",
          foreignField: "_id",
          as: "lounge_join_request",
        },
      },
      {
        $match: {
          "lounge_join_request.lounge": lounge_id,
          "lounge_join_request": { $ne: null },
        },
      }
    ]);
    console.log("🚀 ~ notifications:", notifications);
    // Perform actions based on the notifications
    return notifications;
  } catch (error) {
    console.log("🚀 ~ error:", error);
    // Handle any errors that occur
  }
};

This revised approach should hopefully address the issue. Feel free to provide feedback in the comments section.

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

Fill in the missing keys, values, and data within the JSON object

My JSON data consists of various objects with unique dates and site names. The dataset contains distinct dates such as: 2019-10-01, 2019-10-02, 2019-10-03, 2019-10-04, 2019-10-05. Some dates might be missing for certain sites in the dataset. For example, o ...

Navigating to the bottom of a specific element by scrolling

I am currently working on enhancing a module within the application I'm developing. The goal is to automatically scroll the browser window to the bottom of an element when said element's height exceeds the height of the window. The functionality ...

Keeping datetimepicker current when a date is chosen - a guide

I am currently utilizing the datetimepicker plugin from xdsoft to enable users to select a booking date and time. Check out the documentation for more details. To manage bookings, I have set up a 'fechas' table in my database which stores inform ...

Loading STL files from a buffer instead of a path within Three.js

I'm struggling to showcase a user-uploaded STL file in Three.js. The issue arises when my file is delivered to the front-end through a GET request: res.sendFile(path). Unfortunately, I can't directly utilize this raw data to load the file withou ...

Generating a three-dimensional sphere from flat coordinates with the help of sine and cosine functions

I am trying to achieve mapping a set of 2D coordinates to a 3D surface of a sphere. To accomplish this, I am starting with an array of xy coordinates. Using the following loops, I am generating 20*20 xy coordinates ranging from 0 to 1 on each axis: var p ...

Dealing with Laravel and AJAX - Issue with Loading DIV

I find myself in a perplexing situation. Despite not encountering any errors in my apache logs or browser (chrome), I am faced with an issue that has left me baffled. On a specific page (localhost/admin/networks), I can click on an item from a database-ge ...

Switch between playing and pausing the mp3 audio in the Next application by using the toggle

I am currently working on my website and I have been trying to add a button to the bottom of the page that can play or pause a song using useSound library. The song starts playing when I click it for the first time, however, I am facing difficulty in stopp ...

Sorting `divs` based on the number of user clicks in JavaScript: A simple guide

I've implemented a script that tracks the number of clicks on each link and arranges them based on this count... Currently, everything is functioning correctly except when the <a> tags are nested inside a div. In such cases, the script ignores ...

The process of connecting Mongoose documents

I have three different schemas defined as follows: User var UserSchema = new Schema({ name: String }); Actor var ActorSchema = new Schema({ name: String }); Rating var RatingSchema = new Schema({ actor: { type: mongoos ...

Unable to make a post using vue.js

I am facing an issue while trying to submit form data using "vue-resource" in my code. The error message I receive mentions a problem with the use of this method alongside vue-cli and vuetify. Error [Vue warn]: Error in v-on handler: "TypeError: this.$h ...

The order of execution is not maintained for $.getJSON() calls within the $.each() loop

As I iterate through an HTML table, I am making a $.getJSON() request based on the data in each row. My goal is to retrieve the data from that $.getJSON call and update the corresponding row with it. Unfortunately, when I run my code, it seems to be execu ...

Guide to creating JSDoc for a TouchEvent handler

Looking to improve my shorter-js codebase with JSDoc for TypeScript definitions, but hitting a roadblock. I've implemented the on() function using Element.addEventListener, working well so far. However, when passing a TouchEvent as a parameter for an ...

Steps for transferring JSON data from the controller to JavaScript

Within my cluster Table, there is a column called description which stores cluster coordinates in JSON format. I want to draw multiple cluster polygons on Google Maps using these coordinates. id | description ...

Error in Angular: Trying to read properties of an undefined value, specifically 'classList'

I am attempting to utilize intersection observer in order to apply a class to certain text once it crosses a specific trigger point. Although I have confirmed that my observer is functioning properly as some text changes to blue, there are other texts tha ...

What could be causing the month to be undefined in this Javascript date?

var currentDate = new Date(); var currentMonth = currentDate.getMonth(); var monthArray = [ 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'S ...

Handling asynchronous behavior in the context of conditional statements can be a challenging aspect of

Currently, this code section is passing undefined to if(customerWaiting >0). It's an async issue that I'm struggling to resolve. Despite my efforts and research on other threads, I can't seem to make this basic newbie question work. I&a ...

Jquery on method triggers a single event only

I am encountering an issue with adding and removing a class from an element using the on() method to handle click events. The code works fine on the first click, but subsequent clicks do not trigger the event anymore. Here is the code snippet: $(&apo ...

Is there a way to pass information from Express.js to React without using an API?

My goal is to build a Multi Page APP using both react and express. I find myself uncertain about how to access data sent by express in react without utilizing an API. I am curious if react has the capability to retrieve information stored in HTML props t ...

swap between style sheets glitching

My website features two stylesheets, one for day mode and one for night mode. There is an image on the site that triggers a function with an onclick event to switch between the two stylesheets. However, when new visitors click the button for the first ti ...

Managing State Changes with Redux

Reducers in Redux are primarily designed to be pure functions that take the previous state and an action as arguments, and return a new state object without mutating the previous state. However, it is still possible for developers to directly mutate the st ...