What is the best way to retrieve all documents that share a common ID when using an array of a separate object?

Within my application, I have two models called Alarm and Alert.

The AlertSchema includes a field named created_by that references the object ID of an Alarm.

If I have an array of Alarm objects, how can I retrieve all the corresponding alerts?

I attempted the following, but it did not yield the desired results:

// Retrieve array of alarm objects
Alarm.find({unit: req.unit._id}).exec(function(err, alarms){
   // Use array of alarm objects to find all alerts
   Alert.find({created_by: alarms})

Would it be better to extract the _id from each object and pass them as an argument like shown below:

Alarm.find({unit: req.unit._id}).exec(function(err, alarms){
   var alarm_ids = alarms.map(function(o){return o._id});
   // Use array of alarm objects to find all alerts
   Alert.find({created_by: alarm_ids})

Answer №1

To streamline your data retrieval process, consider leveraging the power of the aggregation framework in MongoDB. By utilizing the $lookup operator, you can seamlessly perform a left outer join operation with another collection, as illustrated in the example below:

Alarm.aggregate([
    { "$match": { "unit": req.unit._id } },
    {
        "$lookup": {
            "from": "alerts",
            "localField": "_id",
            "foreignField": "created_by",
            "as": "alarm_alert"
        }
    },
    { "$unwind": "$alarm_alert" }
]).exec(function(err, result){
    console.log(JSON.stringify(result, null, 4));
});

This approach is efficient due to its atomic nature and utilization of native operators.


If you prefer an alternative method, ensure to incorporate the $in operator for optimal performance. However, be cautious of potential inefficiencies resulting from multiple server calls, such as retrieving alarm objects and querying the alerts collection separately. The following snippet demonstrates how to implement this:

Alarm.find({ "unit": req.unit._id })
      .lean() // <-- return plain javascript objects
      .exec(function(err, alarms){
            var alarm_ids = alarms.map(function(o){return o._id});
            // Use array of alarm objects to find all alerts
            Alert.find({ "created_by": { "$in": alarm_ids } }).exec(callback);
       });

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

When using Jquery, hovering over an element will cause the full title to be

I have created a toggle div that displays an ellipsis (...) when the long title is longer than 30 characters. Now, I want the full text of the long title to appear when hovering over the div. Check out this JS Fiddle for reference. JS $('#popu ...

Tips for managing various errors in an Express API - such as addressing 404, 405, 400, and 500 errors

I am still learning the ropes of node.js and am using the express framework to create a REST API. I am looking to manage multiple errors for my API, specifically handling 404, 405, 400, and 500 errors. While express provides a default error handler, I am u ...

Why are the radio buttons not aligned with the text in the center?

Currently, I am in the process of building a form that includes radio buttons. However, I've encountered an issue where the text next to the radio buttons appears on a different level than the buttons themselves. How can I go about fixing this partic ...

The redirection did not occur as no authorization token was detected

I have two Nodejs applications, one for the front-end and the other for the back-end. The back-end app is secured with token access using express-jwt and jsonwebtoken middlewares. My issue is as follows: when I make a request from the front-end to the bac ...

Having trouble integrating Ionic Native API and Javascript API in one application?

Currently, I am developing an application using Google Maps that utilizes both the Ionic Native Google Maps API and the JavaScript version. The Native API is implemented on a page called home.ts, while the JavaScript API is utilized on a sub-page called de ...

Once the Angular project has been initialized, the Button disable attribute cannot be modified

In my Ionic-Angular project, I am creating registration pages where users input their information in multiple steps. For each step, there is a button that remains disabled until the correct information is entered. An issue arises when transitioning to the ...

What is the best way to switch to a new HTML page without causing a page refresh or altering the URL?

Is there a way to dynamically load an HTML page without refreshing the page or altering its URL? For instance, if I am currently on the http://localhost/sample/home page and I want to switch to the contact us section by clicking on a link, is it possible t ...

Develop a table with dynamic features in Angular according to the number of rows selected from a dropdown menu

I am currently exploring AngularJS 1.6 and tackling the challenge of dynamically populating a table with rows based on the number selected in a dropdown list, ranging from 1 to 12. Here's the code I have up until now: <body ng-controller="myContr ...

Having trouble connecting retrieved database information with AngularJS for display in the view

I am currently working on extracting data from a database and displaying it in a view using AngularJS. I have created a WEM method for this purpose: [WebMethod] public static string fetchNames() { SqlHelper sql = new SqlHelper(); DataTable dt = sql.Ex ...

When using SweetAlert2, a single button will automatically be highlighted as soon as the modal opens

I recently made the switch from using SweetAlert to SweetAlert 2. It took some time to get used to, but I finally achieved my desired outcome, with one small exception. Upon opening the modal, if there is only one button and no other inputs, the button ap ...

encountering an issue with data[i].order not being recognized as a function

I have a task to complete, which involves calling JSON objects based on a search and displaying the results in a bootstrap table. I have been trying to solve this in different ways, but as I am new to JS, I haven't been successful. I have been writing ...

What is the reason behind an index not being able to cover a query that contains an $or expression?

In my MongoDB 3.2 testing, I explored the behavior of "covered queries" and found that while an $or expression is not covered by an index (at least on the same field), substituting it with an $in expression in the query works perfectly fine. The index use ...

JavaScript code can be used to access data from a JSON file and present the flower and color information in separate unordered lists

How can I retrieve data from a JSON file in JavaScript and display flowers and colors in separate unordered lists? I am having trouble adding it. fetch('dataFiles/midterm.json', { method: 'GET', mode: 'no-cors' ...

What is the process for updating an element within a set in MongoDB?

There is a specific entry in my database that looks like this: { "_id": { "$oid": "6241d974a7382732093700d1" }, "userdata": { "Name": "SomeName", "Surname": "SomeS ...

Issue with Mongoose query: Element being pushed twice with $push

I am trying to add a single string into an array from a document in my MongoDB collection using Node.js with Mongoose v5.3.1. First, I input data into an HTML form and then submit it to the server. Here is my HTML code: <form action="/addchat" method ...

Is there a way to make my DIVS update their content dynamically like buttons do, without manually adding an onclick function in the HTML code?

I am currently customizing a WordPress theme that lacks the option for onclick events on div elements. However, I can assign classes and IDs to them. In my design, I have four spans in a row, and when each span is clicked, I intend for the corresponding p ...

What is the best way to enhance a tool-tip with images or legends?

Currently, I have implemented a tool-tip feature which works for a text box. However, the issue is that users are unaware of the presence of the tool-tip for the text box until they hover over it. My question is, how can I make it more obvious to users t ...

transferring data from one HTML file to another using a loop with technologies such as HTML,

As a beginner in front end development, I am finding it a bit challenging at the moment. Here's what I have so far: 1 main HTML file (index.html) 1 JavaScript file (something.js) 2nd HTML file (something.html) Main HTML: <!DOCTYPE html> < ...

The error message "Uncaught TypeError: Cannot read property 'length' of undefined" is commonly encountered in asp.net while using dataTables with zero config

I am encountering an issue with dataTables in my ASP.NET webforms application. The table is generated in the codebehind at Page_Load() and works fine on other pages, but for some reason, I am getting an error message on one specific page: "datatables.min.j ...

Cease the firing of ion-change until the values have been successfully loaded from storage

My settings page contains multiple ion-toggle's. There's an onChange method to update local storage when toggled. Standard procedure involves checking existing values in storage on page load and mapping them to the toggles using ngModel. <tab ...