Failure in querying with Mongo's $lookup results in an empty array

My $lookup operation on schemas is always returning an empty array. What could be causing this issue?

Result Collection

const resultSchema = new mongoose.Schema({
  trial: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Trial',
    required: true
  }
});

Trial Collection

const trialSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  }
});

Aggregate

Result.aggregate([
    {
      $lookup: {
        from: 'trial',
        localField: 'trial',
        foreignField: '_id',
        as: 'x'
      }
    }
  ])
    .exec()
    .then(results => ({ results }))

However, despite following the correct syntax, "x" always ends up as an empty array in the final output.

Answer №1

I just stumbled upon the solution right here:

When using the "from" field in a lookup, make sure to use your collection name instead of the model name. This means it should be a plural word. For example:

from: 'trials'

instead of

from: 'trial'

Answer №2

There was an error in my situation where I mistakenly added a $ sign in front of the collection name:

{$lookup: {
  from: '$users', // <- mistake
  foreignField: '_id',
  localField: 'userid',
  as: 'users'
}},

The correct way to write it is:

{$lookup: {
  from: 'users', // <- correction
  foreignField: '_id',
  localField: 'userid',
  as: 'users'
}},

Answer №3

Ensure that you are using the correct collection name. It appears that in the aggregate function, 'trial' is written in lowercase, while in the results collection, 'Trial' is written with an uppercase 'T'.

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 only able to access MongoDB Atlas remotely from my home, and not from any other

I've been working on developing a full stack MERN app recently. While everything works smoothly when I'm working from home, I encounter issues with the connection to my MongoDB as soon as I change my location (and get a different IP address), for ...

Progressive reloading page with Jquery Ajax upload

I've encountered a strange issue with a Jquery form submit. After the upload completes, the page reloads even though the server hasn't finished processing. The server only returns a JSON success status, so it's not an issue on the server s ...

How can the save method of a DB model be correctly accessed from a route handler function?

Upon using Express.js to create a project, I've observed that the route handler functions are now separated from the main 'app.js' file and placed in './routes/index.js'. In this scenario, how does one go about saving a record to t ...

Utilizing browser and CDNs to import modules in threejs and three-globe for seamless integration

As I delve into the world of threejs and three-globe, I encounter a challenge when trying to integrate them using CDN distributions from unpkg. The issue lies in dealing with modules, and I'm considering the possibility of incorporating a build tool d ...

Tips for increasing a progress bar as data is being added to a database in PHP when a button is clicked

I attempted to implement this code but faced difficulties. Here is the code snippet I used : <script> $(document).ready(function(){ var $progressbar = $("#progressbar"); $progressbar.show(); $('#uploadForm').on ...

The Gravity Simulation Seems to Be Malfunctioning

My current project involves creating a simulation of gravity and its effects. As I embark on this endeavor, I have come across a puzzling issue that has me stumped. The goal is to have my particle's speed increase exponentially based on the gravitatio ...

Get access to a JSON key using forward slashes in Node.js

I'm facing an issue with accessing a property in an object that contains forward slashes. Specifically, I need to access the child key pattern. Unfortunately, my attempts so far have been unsuccessful. Please provide a solution to access the pattern p ...

What is the reason behind the HTML button producing the 'ul' node just once even after being clicked multiple times?

Just to clarify, the code below is successfully doing what I intended. I am currently developing a basic todo application. Each time the button on the page is clicked, it triggers the createListElem() function. The initial line of code in this function ap ...

Node.js and Mongoose encounter difficulties in comparing documents

I am in the process of iterating through an array of documents that I have queried to check if each element is present in another array of documents that I have also queried My model structure includes : var dataTypeSchema = new Schema({ name : Stri ...

Is there a way to use Protractor to test ASP.NET WebForms (not Angular)?

I am completely new to using protractor for testing .NET Applications. I am currently in the process of creating an automation testing script from scratch. The following is the HTML code: <div class = "top"> <span id = "welcome"> <em>Hi& ...

What are the best ways to transfer information between functional components in a React application?

When working with React, data exchange between class-based components can be done using states and props in the following way: App.js import Name from './Name'; import React, { Component } from 'react' export class App extends Compo ...

Step-by-step guide on adding and removing a row from a table with the help of jquery and node js

I just finished creating a table in jade that includes two select boxes and a single text box. However, I encountered an issue where my row addition functionality stops working after the user makes a selection in the first select box and then changes the ...

The AJAX query for validating IDs in a JSP page consistently produces identical outcomes

I have been implementing a feature to check IDs using AJAX in JSP. When a user tries to create a new account, they enter the desired ID and AJAX checks if the ID already exists in the database. If the ID is found, it returns 'n' which is then dis ...

The $_POST value is consistently the final entry within my <tr> element

I'm facing a challenge that has me stuck. I have a basic webpage where I display a table of all Users queried from a database. The idea is that when a user clicks on a table row, they should be redirected to another page where they can edit the select ...

Looking for assistance with a simple Javascript program

My program needs to have a for loop and utilize existing input functions (name and number). Additionally, I need to calculate totals. Users should be able to CANCEL and proceed to doc.write where they can enter their name and number. Furthermore, users s ...

Tips for identifying the presence of a mobile phone notch

My web app, shown in image 1, looks great on most devices. However, when it is launched on a mobile with a notch, like in image 2, a layout problem arises. Using a "safe area" won't work for me because some of my pages need to be fixed at the top, sim ...

Access RSS feeds externally without relying on any third-party libraries or server-side processing

Looking to integrate an RSS parser that can parse feeds using jQuery/JavaScript without relying on the Google Feed API or any server-side solutions. The goal is to have auto-updating RSS feeds without overloading the server with multiple requests from user ...

Tips for transferring the value of ng-model to multiple controllers

Is it possible to access the value of an ng-model from two different controllers? While I am aware that using a service is one way to share data between controllers, I am struggling to figure out how to pass the value of an ng-model to a service for this ...

Implementing context menus on the Material-UI DataGrid is a straightforward process that can enhance the user experience

I am looking to enhance my context menus to be more like what is demonstrated here: Currently, I have only been able to achieve something similar to this example: https://codesandbox.io/s/xenodochial-snow-pz1fr?file=/src/DataGridTest.tsx The contextmenu ...

The functionality of jquery.load() seems to be experiencing issues in Internet Explorer when attempting to load an HTML file

Code $('.form').load('http://'+window.location.hostname+':8423/html/form/form_generate.html/?session='+session); In an attempt to load a html file from a different port on the same server. The original server is accessible ...