What is the best way to perform an inner join in MongoDB using Mongoose and NestJS?

I need to merge customer and product data in the same request from a system using Mongoose with MongoDB in Nest JS.

Here is an example of how the data is structured in the database:

  "_id": "621d2137abb45e60cf33a2d4",
        "product_id": [
            "621cedbf79d68fb4689ef0cb",
            "621cedbf79d68fb4689ef0cb",
            "621cedbf79d68fb4689ef0cb"
        ],
        "client_id": "621d19f890ec693f1d553eff",
        "price": 597,
        "__v": 0

Below is my service implementation:

  findAll() {
    return this.sealsModel.find().exec();
  }

I tried the following approach, but it didn't work as expected:

findAll() {
    var a = this.sealsModel.find().exec()
    return this.sealsModel.aggregate([{
        $lookup: {
          from: 'seals',
          localField: 'client_id',
          foreignField: '_id',
          as: 'client' 
        }
    }])            
    .exec()
}

The above method returned the following output:


 "_id": "621d3e0a1c3bcac85f79f7cc",
        "product_id": [
            "621cedbf79d68fb4689ef0cb",
            "621cedbf79d68fb4689ef0cb",
            "621cedbf79d68fb4689ef0cb"
        ],
        "client_id": "621d19f890ec693f1d553eff",
        "price": 597,
        "__v": 0,
        "client": []

Answer №1

Instead of using Mongo's $lookup operator, you can opt for Mongoose's populate function. To utilize it effectively, the first step is to update your model.

Your client model should resemble this:

// /models/Client.js
const mongoose = require("mongoose");

const clientSchema = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  ... // include your other fields here
});

module.exports = mongoose.model('Client', clientSchema);

The important detail to note is the reference name 'Client' used in the last line of the model.

You mainly need to make changes in your Seal model :

// /models/Seal.js
const mongoose = require("mongoose");

const sealSchema = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  client_id: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Client" // Same name as given to the client model above
  }
});

module.exports = mongoose.model('Seal', sealSchema);

Then, in your code, you can use:

const Seal = require("YOUR_PATH/models/Seal.js")

Seal.find().populate("client_id")

An important thing to remember is that your model represents the mongo ID as a string

"_id": "621d3e0a1c3bcac85f79f7cc",
"client_id": "621d19f890ec693f1d553eff", <---

Ensure that the field client_id is of type ObjectId or it will not function properly:

"client_id": ObjectId("621d19f890ec693f1d553eff")

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

I am looking to quietly install MongoDb 3.6 without the inclusion of Compass

Struggling to set up MongoDb 3.6.2 community in passive mode without including MongoCompass. Can't find any guidance on how to do this in the documentation. ...

Unable to proceed with iteration

I am encountering an issue with the ng-repeat directive while working on it. As a beginner, I am struggling to resolve it on my own. var myModule = angular.module("myFirst",[]); myModule.controller("cont", function($scope){ var employees = [ {name: "Ma ...

Utilizing AngularJS to create bound checkboxes

I am struggling with two checkboxes, one with Data Binding and the other without Data Binding. The code snippet below illustrates this: <html ng-app="notesApp"> <head><title>Notes App</title></head> <body ng-contro ...

Odd behavior of the "for in" loop in Node.js

It seems like I'm struggling with the use of the "for in" statement. When working with a JSON document retrieved from a mongodb query (using nodejs + mongoose), its structure looks something like this: [{ "_id":"596f2f2ffbf8ab12bc8e5ee7", "da ...

Troubleshooting problem with ajax and extracting information from a dataset

I am in urgent need of retrieving the $BarcodeID when I click on the DELETE button on my website. My goal is to retrieve this 13-digit number in order to delete the corresponding row from the item Database (Sql). I understand that once I have the correct ...

Implementing a custom button specifically for the month view in JavaScript FullCalendar

I have successfully added a custom button to my JavaScript full calendar code, but I would like this button to be displayed only in the month view. $(document).ready(function() { var calendar = $('#calendar').fullCalendar({ editable: tru ...

When attempting to navigate to a new route with a query, I encounter the error message "NavigationDuplicated: Avoided redundant navigation to current location."

I'm facing an issue with my navigation header setup. It includes a search bar that redirects users to the home view with the search query as a parameter. Here's the code snippet for reference: <template lang="html"> <div cl ...

Which is better: Using Multiple Documents or Embedded Documents in Mongodb?

As I work on developing a social networking platform similar to Twitter, one of the key features is the notification system. To store these notifications, I have decided to use MongoDB. My plan is to limit each user to a maximum of 100 notifications, with ...

Update the text on the button

I stumbled upon part of the solution at :jQuery change button text My quest is to find out how to toggle the button text. I attempted using the class method to switch between "show teams" and "hide teams". Simply changing the text property on button click ...

Explore the wonders of our solar system using three.js!

I am embarking on my first project using three.js to create a miniature solar system consisting of 1 star, 2 planets, and 1 moon orbiting each planet. As a beginner to both three.js and JavaScript in general, I am eager to learn. Currently, I have success ...

Renovating code with the .catch(handleError) function leads to an UnhandledPromiseRejectionWarning

I need to refactor my catch block to use a common approach for multiple requests, but I am encountering an UnhandledPromiseRejectionWarning: ReferenceError: next is not defined. Below is a snippet of the code. user.save() .then(user => { }) ...

Issue with Quantity Box not displaying values in Shopify store

I am currently seeking assistance with resolving an issue I have encountered on a Shopify theme that I recently customized. The problem lies within the quantity box on the live site where despite being able to adjust the quantity using the buttons, the act ...

The Three.js raycaster is already picking up on objects before I even start moving the mouse

I'm experimenting with the Three.js raycaster and have created a grid of planes that are supposed to start off yellow and turn red when you hover over them with the mouse. However, the issue I'm facing is that when I run the script, all the plane ...

Ensuring validity with Vuelidate for customizable fields

There's a form where fields are dynamically added on a click event. I want a validation error to appear when the field value is less than 9 digits after changing or blurring it. The issue is that since the fields are created dynamically with the same ...

Choose an XPath formula that will target every single element, text node, and comment node in the original sequence

How can we write an XPath expression that selects all elements, text nodes, and comment nodes in the order they appear in the document? The code below selects all elements but not text nodes and comment nodes: let result = document.evaluate('//*&apo ...

Highlight dates in Vue.js that are overdue using a date filter

Currently, I have a Vue filter set up to display dates in a visually appealing way. However, I am looking to enhance the filter by adding a feature that would highlight dates in red if they are overdue (meaning the date is earlier than the current date). I ...

jQuery: Modifying the Style of obj "th" Element

I am looking to update the style of my selection using jQuery. After using this module to retrieve all items, I have a list of cells with new coordinates. //cell list with new coordinates cl = Object {0-0: th, 0-1: th, 0-2: th, 0-3: th, 1-0: td…}, id = ...

The presence of asynchronous JavaScript can lead to errors due to missing functions in JavaScript

I've encountered an issue with a jQuery script that I modified by adding an ASYNC attribute. Surprisingly, it functions correctly in Firefox but encounters intermittent failures in both Chrome and IE browsers. Here's the PHP code snippet respons ...

Is it possible to set the cursor back to its default position in MongoDB?

// Adding three new entries to the collection named "foo" db.getCollection("foo").insertMany([ {"name" : "john" , "age" : 25}, {"name" : "jane" ,"age" :28}, {"name" : "adam" , "age" : 30}]) // initialize cursor var cursor = db.getCollection("foo").find() ...

Instructions for generating multiple components in React when an array is not at your disposal

In the process of developing a Tic-Tac-Toe game, I am in need of creating 9 empty squares. Currently, I have a ul element and 9 li elements representing each square in the game. The issue is that there is no array available for looping through and generati ...