Unforeseen Name Conflict issue

The issue I'm facing with Mongo involves an identifier in the forEach loop within the second aggregation. Despite my best efforts, I cannot pinpoint which identifier is causing the problem. After staring at it all day, I realize that fresh eyes are needed to help me out. Any assistance will be greatly appreciated by my eyes, brain, and heart! use events

var affected = []
var start = new Date()
var end = new Date("2017-06-01T00:00:00Z")

for (var dayPast = new Date(start); start >= end; start.setDate(start.getDate() - 1)) {
  dayPast.setDate(dayPast.getDate() - 1)

  var results = db.completion_event.aggregate([{
    $match: {
      applicationId: 1,
      dateCreated: {
        $lt: start,
        $gte: dayPast
      },
      "data.name": "eventComplete",
      "data.metadata.aggregationId": /identifying_string.*/,
      "data.sponsorIds": {$in: [1,2,3,4,5,6]}
    }
  }, {
    $project: {
      customerId: 1,
      dateCreated: 1,
      "data.metadata.aggregationId": 1
    }
  }, {
    $group: {
      _id: {
        customerId: "$customerId",
        dateCreated: "$dateCreated",
        aggregationId: "$data.metadata.aggregationId"
      },
      "total": {
        $sum: 1
      }
    }
  }], {
    $limit: 1
  }, {
    allowDiskUse: true
  }).toArray()

  results.forEach(function(event) {
    use rewards

    var state = db.customer_state.find({customerId: event._id.customerId}).sort({_id: -1}).limit(1).toArray()[0]
    var planId = state.planId
    var plan = db.plan.find({id: planId}).toArray()[0]

    if(plan.schedule.activeStart < new Date() < plan.schedule.activeEnd) {
      use events
      var latest = db.completion_event.aggregate([{
        $match: {
          applicationId: 1,
          customerId: event._id.customerId,
          dateCreated: {
            $gte: plan.schedule.activeStart
          },
          "data.name": "outterEventComplete",
          "data.metadata.aggregationId": event._id.aggregationId
        }
      },
      {
        $project: {
          consumerId: 1,
          dateCreated: 1,
          "data.sponsorIds": 1,
          "data.metadata.aggregationId": 1
        }
      }], {
        $limit: 1
      }).toArray()
      affected.push(latest[0])
    }
  })
}
print(affected)

The source of my frustration:

E QUERY    SyntaxError: Unexpected identifier

Answer №1

My prediction is on utilizing rewards and events. These are shortcuts in the shell, not intended for use within regular JavaScript code. Here's a different approach:

Instead of employing use rewards to switch databases, try this instead


var rewards_db = db.getSisterDB('rewards');
rewards_db.customer_state.find(...)

The same applies to events, of course.

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 ensure that all nested asynchronous jQuery AJAX requests are complete before proceeding?

Currently, I am utilizing jQuery to handle a series of asynchronous AJAX requests in a loop. I am aware that I can wait for all of them to be completed by utilizing the convenient '$.when.apply(array_of_requests).then()' method. However, I also ...

Encountering issues when using array.map with null entries in a react application

Struggling to iterate over the location array and map it? Despite several attempts, handling the null object within the array seems challenging. What am I missing here? While using a for loop resolves the issue, the map function is proving to be a roadbloc ...

The search engine results page (SERP) is only displaying the homepage and not any of the subpages

Check out this search to see that only my main page is indexed. Why aren't Google and other search engines picking up arda-maps.org/about/ and the other subpages? Is my deep linking technique incorrect? Do the search engines just need more time? If s ...

What could be causing the code to malfunction and prevent window.ethereum from working properly?

While attempting to develop a dApp, I have encountered an issue with the browser in Visual Studio Code not recognizing the Ethereum connection, despite having installed MetaMask on the active browser session. Here is a snippet of my code used to test the c ...

Utilize vue-resource for updating information in the database

Within my Vue component, I have the following data setup: data() { return { revenueChart: '', limit: 12, labels: '', datasets: '' } }, In addition, there is a method that utilizes vue- ...

Controlling dynamic fields within a web page - Utilizing Postgres and MongoDB databases

My application utilizes MongoDB and PostgreSQL as databases, with AngularJS for the UI. A key requirement is the ability to dynamically add fields (columns) on pages, allowing users to define their attributes when adding these fields to the system. In add ...

When working with TextareaAutosize component in MUI, an issue surfaces where you need to click on the textarea again after entering each character

One issue that arises when using TextareaAutosize from MUI is the need to click on the textarea again after entering each character. This problem specifically occurs when utilizing StyledTextarea = styled(TextareaAutosize) The initial code snippet accompl ...

Receiving an error message and identifying the specific line number within the catch

try{ cause error } catch(err){ console.log(err.lineNumber) //or console.log(err.line) } The error object has various properties like err.name, err.stack, and err.message, but I have been unable to find a way to log the line number of the error ...

Is it possible to transfer data from a JavaScript file to the Express server without relying on a form submission?

As a newcomer here, I apologize if I overlook any best practices. Currently, I am in the process of developing a sudoku game using express, JavaScript, HTML, and mongoDb. My current challenge involves setting up a statistics system. My goal is to send da ...

Steps for running a script within a Spring Boot application that utilizes MongoDB:

In my spring boot application utilizing mongoDB as the database, I have encountered an issue with inconsistent data in a basic collection. Specifically, I have a decimal property named "value" which contains values of both "string" and "double" types. I ne ...

Steps for updating a property of an object using a function

I am working on a function that resets the deepest value of an object with variable depth to 0. I need this function to update the object's property outside of its scope. var data = { '1': { '10000': { ...

Having trouble locating an element, Sammy?

I am encountering an issue while using Sammy for my SPA. The error message I receive is: [Sun Mar 29 2020 17:37:19 GMT+0300 (Eastern European Summer Time)] #main 404 Not Found get / Error: 404 Not Found get / at Sammy.Application.error (sammy-latest ...

Tips for extracting information from a JSON file using $routeParams in AngularJS

https://i.stack.imgur.com/NQCpy.png I am currently encountering an issue with retrieving data using $routeparams. Here is a description of my problem: Retrieving the URL to redirect console.log($routeParams); console.log($routeParams.json_url); $.getJS ...

When refreshing a page in Next.js, the loading indicator does not properly turn off

I'm currently working on my portfolio using next.js and I have implemented a 'loading' state to prevent displaying partially loaded gallery images. The 'loading' state should turn off (set to 0) once all the photos are fully loaded ...

Node.JS Error: "util.TextEncoder is not a constructor" was thrown

After using browserify to bundle my js files, I encountered an error that says Uncaught TypeError: util.TextEncoder is not a constructor at Object.1.util (bundle.js:3) at o (bundle.js:1) at r (bundle.js:1) at bundle.js:1 Below are the init ...

Listener for body keystrokes

Is there a way to trigger a function when the space bar is pressed on the page, without it being called if an input field is focused? Any thoughts or suggestions? The current code triggers the function even when an input bar is focused: $(document).keydo ...

React to the Vue: Only activate the event if the key is pressed twice consecutively

In my application, I am creating a unique feature where users can trigger a window to appear by inputting the symbol @ (shift + 50). This will allow them to access predefined variables... <textarea @keyup.shift.50="showWindow"></textarea> My ...

Tips on utilizing the identical template in ngIf

I need to display different templates based on certain conditions. For example: <template [ngIf]="item.url.indexOf('http') == -1"> <a class="ripple-effect" [routerLink]="[item.url]" *ngIf="isUserLoggedIn == true" > ...

I'm trying to figure out how to make HTML tags display within a React/Next <head> element

I inherited a React/Next project filled with spaghetti code. The previous developer did not prioritize SEO, and I am still learning React. Now, my main focus is getting tags to render in the Component. <Head> <meta key="data-tes ...

Locate elements within an array where a specific attribute includes the specified search term

While working with Javascript, I encountered an issue where the function I wrote to retrieve objects from an array was not returning all the data that met the query criteria. In my dataset, which originally contained 1536 objects, there are several jokes ...