Mongoose: $lookup followed by $project is not displaying a specific field

I am working with two models named user.js and schedule.js. I am trying to implement a query using the $lookup operator to effectively "join" data from these models. However, after applying the $lookup, I am using the $project operator to select specific fields to display in the query result. Unfortunately, the fields scheduleStart and scheduleEnd are not appearing in the final output.

User.js (model)

  name: {
        type: String,
        required: true
    },
    firstName: {
        String
    },
    lastName: {
        String
    },
    storeKey: {
        type: String,
        required: true
    },
    avatar: String,
    birthday: String,
    phone: {
        type: String
    },
    doc: String,
    email: {
        type: String
    },...

Schedule.js (model)

 service: {
    id: {
      type: String
    },
    name: {
      type: String,
      required: true
    },
    filters: [String]
  },
  info: {
    channel: {
      type: String,
      required: true,
      default: 'app'
    },
    id: String,
    name: String
  },
  scheduleDate: {
    type: String,
    required: true
  },
  scheduleStart: {
    type: String,
    required: true
  },
  scheduleEnd: {
    type: String,
    required: true
  },

My query

 User.aggregate([{
      $match: {
        storeKey: req.body.store,     
      }
    },
    {
      $group: {
        _id: {
          id: "$_id",
          name: "$name",
          cpf: "$cpf",      
          phone: "$phone",
          email: "$email",
          birthday: "$birthday",
          lastName: "$lastname"      
        },
        totalServices: {
          $sum: "$services"
        },    
      }
    },
    {
      $lookup: {
        from: "schedules",
        localField: "_id.phone",
        foreignField: "customer.phone",
        as: "user_detail"
      }  
    },  
    {
      $project: {
        _id: 1,
        name: 1,
        name: 1,
        cpf: 1,      
        phone: 1,
        email: 1,
        birthday: 1,
        totalServices: 1,
        totalValue: { "$sum": "$user_detail.value" },
        scheduleStart: 1,
        scheduleEnd: 1,
        count: {
          $sum: 1
        }
      }
    }   
  ])...

Result of my query:

count: 1
totalServices: 89
totalValue: 2374
_id:{
birthday: "1964-03-18",
cpf: "319335828",
email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6309070c0623040e020a0f4d000c0e4d0111">[email protected]</a>",
id: "5b1b1dcce1ab2a8eb580f",
name: "Jonh Doe",
phone: "11996370565"
}

Answer №1

If you want to implement the following $project stage using the $arrayElemAt aggregation method

{ '$project': {
  '_id': 1,
  'name': 1,
  'cpf': 1,      
  'phone': 1,
  'email': 1,
  'birthday': 1,
  'totalServices': 1,
  'totalValue': { '$sum': '$user_detail.value' },
  'scheduleStart': { '$arrayElemAt': ['$user_detail.scheduleStart', 0] },
  'scheduleEnd': { '$arrayElemAt': ['$user_detail.scheduleEnd', 0] },
  'count': { '$sum': 1 }
}} 

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

Fetch the user's email address from Auth0 using an asynchronous function

I am trying to load the user's email from Auth0 and store it in a constant. However, I am getting an arrow. I cannot identify the error. Can anyone help me find a solution? const userEmailInfo = async () => { auth0Client = await auth.createClien ...

AngularJS: Functions may return false due to the asynchronous nature of services

Template Overview: <div data-ng-if="budgetSummaryExists()"> <span>You currently have no budget.</span> <button type="button" class="btn btn-danger" data-ng-click="setRoute('budgets')">Creat ...

A guide on displaying a text file from a URL in a reactjs application

When utilizing the code provided below, I have successfully managed to display the content of a local text file on a webpage. However, when attempting to render a text file from a URL, the state becomes null resulting in an empty display. In order to ren ...

Create and adapt dynamic tiles to fit within the available width

I am looking to create a dynamic tile (div) that adjusts based on the number of users available, similar to how it works in Microsoft Teams meetings. For example, if there is only one user, the div should occupy the full screen. When there are two users ...

Can a form be submitted to two different pages based on the button name?

I have a form that directs to another page and performs various database operations. <form id="form1" method="post" action="goes_to_page1.php" onsubmit="return checkformvalidation();"> <input type="text" id="field1" name="field1" onblur="checkva ...

Oops! An error has occurred: The requested method 'val' cannot be called on an undefined object

I am struggling with this issue. This is the code that I am currently working on: http://jsfiddle.net/arunpjohny/Jfdbz/ $(function () { var lastQuery = null, lastResult = null, // new! autocomplete, processLocation = function ...

React Native - Invariant Violation: Objects cannot be used as a React Child (Utilizing Node.js for the backend)

Trying to calculate the total sum of orders and their quantity using Node JS on the backend. However, encountering issues with the fetch functions not working properly or missing something unknown. The API works as expected when tested in Postman, but err ...

tips for applying a where clause on a jsonb column in an included table with sequelize

I currently have 2 tables stored in a postgres database. Table_A -------- id BIGINT metadata JSONB Table_B -------- id BIGINT a_id BIGINT metadata JSONB Data Table_A id | metadata 1 | {'gender': 'Male', 'name': 'xyz&ap ...

Managing visual content on a live server

As a beginner working with MERN, I have managed to deploy the frontend and backend separately for testing. When a user signs up, they can choose a profile picture. This process works smoothly on localhost as the image successfully gets added to the mongodb ...

generate code to automatically output the content of a website

I'm in the process of creating a program that automatically navigates to a website and prints a page. Unfortunately, I'm encountering difficulties in getting it to function properly. I've attempted using the selenium chrome driver, but with ...

Exploring the functionality of window.matchmedia in React while incorporating Typescript

Recently, I have been working on implementing a dark mode toggle switch in React Typescript. In the past, I successfully built one using plain JavaScript along with useState and window.matchmedia('(prefers-color-scheme dark)').matches. However, w ...

Guidelines for accessing the Coinbase exchange API from a localhost

Following the instructions in the Coinbase Cloud documentation, I tried running this code on the client side using JavaScript: const options = { method: 'GET', headers: { Accept: 'application/json', 'cb-access-key&ap ...

Using JQuery to manipulate `this`, its children, its siblings, and more

Can anyone help me determine the most effective way to send data from a get request to a specific div? My challenge is to send it only to a div that is related to the one triggering the action. For example, when I click on the message_tab, I want to send t ...

Using custom class instances or objects within Angular controllers is a simple process

Using three.js, I have created a class called threeDimView that houses my scene, camera, and other elements. In my JavaScript code, I instantiate a global object of this class named threeDimView_. threeDimView_ = new threeDimView(); Now, I wish to displa ...

Transferring information from Python to JavaScript and receiving a response

Currently, I am working on sending JS data, particularly images that have been collected by a Python file. My goal is to send these images from Python to JS so that JS can perform a certain action (which I will be coding). Afterwards, the final result ne ...

Utilize custom SMTP with JavaScript to dispatch emails

I'm wondering if it is possible to send emails using just JavaScript (I am working on a PhoneGap app). I envision a scenario where I can connect to a specific SMTP server with a login and password, and then send emails using that connection. I have al ...

When I try to alter HTML using JS, I encounter an undefined error related to AngularJS

Using this specific function: function adjustContent(elemento){ if (document.getElementById(elemento).innerHTML.indexOf('&#10004;')>0){ document.getElementById(elemento).innerHTML=document.getElementById(eleme ...

Is it possible to export multiple named exports in a single set without changing how variables are called?

In my constants file I have: export const CONSTANT1 = 'CONSTANT1'; export const CONSTANT2 = 'CONSTANT2'; export const CONSTANT3 = 'CONSTANT3'; export const CONSTANT4 = 'CONSTANT4'; export const CONSTANT5 = 'CONS ...

Exporting functions using reactjs and babel

I'm currently working on a project that involves using reactjs, transpiled by babel with es2015 and react transforms configured in my .babelrc file. In the initial stages of refactoring, I realized that many of the classes should actually be functions ...

Is it possible to retrieve the parent object?

My code snippet is as follows, and I'm struggling to access the data object from within the innerFn function. Is there a way to accomplish this? export default { data: { a: "a", b: "b" }, fn: { innerFn: () => co ...