Incompatibility in Parse Cloud Code syntax leading to query failure

We are in need of an aggregation pipeline that utilizes various stages like: addFields, lookup, group, and unwind. However, there seems to be a discrepancy when converting the MongoDB Compass syntax into Parse Cloud Code JavaScript calls, as we are not achieving the expected results.

The code exported from MongoDB Compass for "Node" appears as follows:

[
  {
    '$addFields': {
      'user': {
        '$substr': [
          '$_p_pUser', 6, -1
        ]
      }
    }
  }, {
    '$lookup': {
      'from': '_User', 
      'localField': 'user', 
      'foreignField': '_id', 
      'as': 'userobject'
    }
  }, {
    '$addFields': {
      'username': '$userobject.username'
    }
  }, {
    '$unwind': {
      'path': '$username'
    }
  }, {
    '$group': {
      '_id': '$username', 
      'total': {
        '$sum': '$score'
      }
    }
  }
]

There are distinct syntax variations between the raw MongoDB query and what is expected for Parse Server calls. Below is the converted syntax that should function (to the best of my understanding):

var pipeline = 
    {
        addFields : 
        { 
            user : '$pUser.objectId', // accessing the user object id differently than previous syntax shown
            username: '$userobject.username'
        },
        lookup : {
            from: '_User',
            localField: 'user',
            foreignField: '_id', // using "_id" instead of "objectId" due to specific field naming in the lookup table
            as: 'userobject'
        },
        unwind : { path: '$username' },
        group : {
            objectId: '$username',
            total : {
              $sum : '$score'
            }
        }
    };
    var pipelineResults = await gameTableQuery.aggregate(pipeline);

Expected Output

The desired output aims to link the current table's user pointer (pUser) with the User table, then group by username whilst calculating the sum of scores.

Actual Output

In the scenario where searching for the _id during the lookup stage, no entries are returned.

Replacing the lookup stage foreignField with objectId retrieves all users instead of only those matching the local field.

lookup : {
    from: '_User',
    localField: 'user',
    foreignField: 'objectId',
    as: 'userobject'
}

It appears there might be a syntax error occurring during the translation between MongoDB syntax and the Parse Server aggregate pipeline syntax.

Answer №1

Is it possible for you to create a test that fails like this?

fit('sort by pointer', (done) => {
    const pointer1 = new TestObject({ value: 1});
    const pointer2 = new TestObject({ value: 2});
    const pointer3 = new TestObject({ value: 3});

    const obj1 = new TestObject({ pointer: pointer1 });
    const obj2 = new TestObject({ pointer: pointer2 });
    const obj3 = new TestObject({ pointer: pointer3 });
    const pipeline = [
      {
        project: {
          tempPointer: { $substr: [ "$_p_pointer", 11, -1 ] }, // Remove TestObject$
        }
      },
      {
        lookup: {
          from: "test_TestObject",
          localField: "tempPointer",
          foreignField: "_id",
          as: "tempPointer"
        }
      },
      {
        unwind: {
          path: "$tempPointer",
        }
      },
      { sort : { "tempPointer.value" : -1 } }
    ];
    Parse.Object.saveAll([pointer1, pointer2, pointer3, obj1, obj2, obj3]).then(() => {
      const query = new Parse.Query(TestObject);
      return query.aggregate(pipeline);
    }).then((results) => {
      expect(results.length).toEqual(3);
      expect(results[0].tempPointer.value).toEqual(3);
      expect(results[1].tempPointer.value).toEqual(2);
      expect(results[2].tempPointer.value).toEqual(1);
      console.log(results);
      done();
    }).catch((error) => {
      console.log(error);
      done();
    });
  });

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

What is the best way to specify a type for an object without altering its underlying implicit type?

Suppose we have a scenario where an interface/type is defined as follows: interface ITest { abc: string[] } and then it is assigned to an object like this: const obj: ITest = { abc: ["x", "y", "z"] } We then attempt to create a type based on the valu ...

"Running experiments with Google Ads and Google Analytics scripts results in a blank page being displayed

Currently, I am working on a plain HTML file and conducting tests to ensure that the Google Ads and Analytics scripts are functioning correctly before implementing them on other pages. A colleague who has an AdSense account provided me with the script code ...

Manage and update events in the Angular Bootstrap Calendar

For the past few days, I have been working on integrating a calendar into my project. I decided to repurpose an example provided by the developer. One issue that I've come across is related to the functionality of deleting events when using the dropdo ...

Making a chain of multiple AJAX requests using jQuery

My current challenge involves retrieving data from select options on a website using JavaScript. Specifically, I am trying to obtain a list of zones within my country from a website that has this information. The issue I am facing is the hierarchical disp ...

Trouble uploading an audio blob as a base64 string using Google Drive API with the drive.files.create method - File ID could not be located

My current challenge involves sending an audio blob to a specific Google Drive folder. To accomplish this, I convert the blob into a file before initiating the transfer process. However, I have encountered an error from the beginning: Error: File not fo ...

Tips for connecting Vue data to a dropdown menu

While diving into Vue.js, I'm encountering a puzzling issue. Despite receiving data from the server (5 records), it's not populating the <select> element properly. Instead of multiple options, all I see is a single one displaying {{dept.DNa ...

Exploring the intersection of points within an aframe

When working with a point in 3D space, it can be difficult to interact with it using a cursor or mouse. However, in three.js, there is an example (https://threejs.org/examples/webgl_interactive_points.html) where the mouse can easily interact with points ...

Is there a way to remotely access and read text files stored on a server using either JavaScript or Ajax from an IIS6.0 Virtual directory?

Is it possible to use JavaScript or Ajax to read the text from a file on a remote machine (from IIS6.0 Virtual directory) and then copy it into a specific folder on the client machine? ...

Exploring the Diversity of Forms with Ajax and JQuery

$(document).ready(function () { $("#addrow").click(function () { var newRow = '<tr><td><input type="text" class="item_code form-control" placeholder="Item Code" name="item_code[]"></td><td><input type="text" ...

Access the OpenWeatherMap API to retrieve the weather forecast for a single time slot within a 5-day period

Utilizing the openweathermap api, I am retrieving a 5-day/3-hour forecast here. The API call provides multiple results for each day with data available every 3 hours. For the full JSON response, you can access it here. Please note that the API key is only ...

What is the best way to search for documents that have all conditions met within a sub-array entry?

My rolesandresponsibilities collection document is displayed below: [{ "_id": { "$oid": "58b6c380734d1d48176c9e69" }, "role": "Admin", "resource": [ { "id": "blog", "permissions": [ " ...

Is there a way to dynamically incorporate line numbers into Google Code Prettify?

Having some trouble with formatting code and inserting/removing line numbers dynamically. The line numbers appear on the first page load, but disappear after clicking run. They don't show at all on my website. I want to allow users to click a button a ...

Sort by label using the pipe operator in RxJS with Angular

I have a situation where I am using an observable in my HTML code with the async pipe. I want to sort the observable by the 'label' property, but I'm not sure how to correctly implement this sorting logic within the pipe. The labels can be e ...

Exploring the power of Google Maps Radius in conjunction with AngularJS

I am currently developing an AngularJS app that utilizes a user's location from their mobile device to create a dynamic radius that expands over time. You can view the progress of the app so far by visiting this link: . The app is functional, but I a ...

Utilizing jQuery to toggle a dropdown box based on multiple checkbox selections

After conducting a search, I came across a helpful resource on Stack Overflow titled Enable/Disable a dropdownbox in jquery which guided me in the right direction. Being new to jQuery, I found it useful to adapt code snippets to suit my needs. Now, my que ...

Having difficulty populating the token in the h-captcha-response innerHTML and g-recaptcha-response innerHTML

I am attempting to use 2captcha along with Selenium and Python to bypass an Hcaptcha. After receiving my 2captcha token, I attempt to input it into the textareas labeled 'h-captcha-response' and 'g-captcha-response'. However, this app ...

Getting the ID name from a select tag with JavaScript - A quick guide!

Can you help me retrieve the id name using JavaScript when a selection is made in a select tag? I have tried running this code, but it only alerts undefined. For instance, if I select bbb in the select tag, I should be alerted with 2 Any suggestions on ...

Express JS encountering Firebase Google Sign-In glitch

Whenever a user clicks a button on the HTML page, this function is triggered. The function resides in auth.js and it is called from the server.js page. auth.js const firebase = require("firebase"); static googleSignIn(req,res){ firebase.aut ...

How to disable the onChange event in PrimeNG p-dropdown?

I'm currently utilizing PrimeNG's dropdown component. Each option in the list includes an icon that, when clicked, should trigger a specific method. Additionally, I need to execute another method when the onChange event of the dropdown is trigger ...

Different ways to modify the color of a chart using am4chart

I am using am4chart to create a line chart on my website. The background of the website is black, so I need to make the chart white. https://i.sstatic.net/eHMw9.jpg I have tried changing the chart fill when creating the chart, but it didn't work at a ...