Error Saving MongoDB Scheduled Trigger - How to Proceed?

This situation is becoming really frustrating. I decided to set up a scheduled trigger to run every 24 hours. It essentially extracts data from one collection, processes it, and then appends the information to another collection. Interestingly, the code works perfectly fine while the function is running. However, I am unable to save the changes due to some obscure "runtime" errors showing up. This issue persists even though the function execution seems flawless and returns the expected results.

Error Message in Console:

> result (JavaScript): 
EJSON.parse('{"$undefined":true}')

I suspect that this error might be related to the return statement. When I try to return null, the following happens:

> result: 
null
> result (JavaScript): 
EJSON.parse('null')

Upon attempting to save, I encounter the following message at the top of the page:

runtime error during function validation

Function Implementation:

exports = async function() {
  const usersCol = context.services.get("SchoologyDashCluster").db("SchoologyDashApp").collection("users");
  const gradesCol = context.services.get("SchoologyDashCluster").db("SchoologyDashApp").collection("grades");
  var usersCusor = await usersCol.find( ).toArray();
  var gradesCusor = await gradesCol.find( ).toArray();
  let insert = [];
  for (let i = 0; i < usersCusor.length; i++) {
    var user = usersCusor[i];

    var userSavedGrades = gradesCusor[i].grades
    var currentGrades = await getGrades(user.schoologyUID, user.consumerKey, user.secretKey);
    
    var lastGraded = NaN;
    let index = gradesCusor[i].grades.length - 1;
    
    while (true) {
      if (gradesCusor[i].grades[index].changed == 1) {
        lastGraded = index;
        break
      }
      index = index - 1;
    }
    console.log(lastGraded)
    if (userSavedGrades[lastGraded].grades.ga == currentGrades.ga){
      currentGrades = { changed : 0, time: new Date().getTime()};
    } else {
      currentGrades = {changed : 1, grades: currentGrades, time : new Date().getTime()};
    }
    
    
    gradesCol.updateOne(
      {"user" : user._id},
      {"$push" : {"grades" : currentGrades}}
    )
  }
  // return usersCol.find( );
  
  
  return null;
};

Answer №1

Realizing my mistake was humbling as the solution turned out to be quite straightforward. I had mistakenly placed the module imports at the top of the document, but the correct placement should have been within the exports function. Here is the corrected version:

exports = function (x,y,z) {
 const http = context.http;
 return;
}

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 can be done to resolve the error message "Matchong query does not exist"?

Recently, I've been working on developing a like system similar to Instagram's using Django and Ajax. However, after completing the code, I encountered a frustrating error message that read "Post matching query does not exist." Despite thoroughly ...

Storing tweets in a mongodb database using nodejs

I have successfully written a code using nodejs to fetch data from twitter. Now, I am facing difficulty in storing it in mongodb. Can someone please provide me with step-by-step guidance on how to achieve this? I am unable to do it on my own. var app = ...

Steps for executing a Node script are as follows:

My task is to execute a node script that will remove an object from an external API. This can be achieved by running the following command: node server.js Customer55555 Upon execution, the specified object should be deleted successfully. To interact wit ...

Unit Testing in Aurelia: Creating a Mock for a Custom Resolver

Below is the snippet of code that I am currently trying to test: import {inject} from 'aurelia-framework'; import {CrudResource, DependencyFactory} from 'utils'; let commonData = {}; @inject(DependencyFactory.of(CrudResource)) ...

The intersectsBox function unexpectedly returns true instead of false

I recently came across a tutorial on MDN that discussed the intersection of bounding boxes. Intrigued, I decided to try out the code snippet provided: const testBoxGeometry = new THREE.BoxGeometry(3, 3, 3); const testBoxMaterial = new THREE.MeshBasicM ...

The index falls outside the acceptable range

I've encountered a problem with the Tone.Analyzer in Safari 10.1. When setting the Tone.Analyzer with a size > Math.pow(2, 10) (1024), I'm faced with the following error: IndexSizeError (DOM Exception 1): The index is not in the allowed range. ...

Can Next.js 13 components maximize performance by utilizing server and client components simultaneously? What is the best approach to achieve this?

Introduction Currently, I am exploring server and client components in Next.js 13 and looking to incorporate them into my project. One of the key features is a container component that utilizes react-intersection-observer to track which section is visible ...

The basic generator appears to be malfunctioning

Recently, I created a basic generator: function geni() { for(var i = 0; i < 10; i++) { yield i; } } Unfortunately, I encountered an error message: SyntaxError: missing ; before statement [Break On This Error] yield i; My devic ...

Having trouble with drawImage function in HTML5 Canvas on Firefox?

This script is successfully running on Chrome, Opera, Yandex, and IE browsers, but it encounters an issue when trying to run on Firefox. In the code, "el" refers to my image (which is stored like this <img src="background.png"). fadeInEffect: function ...

Discovering the destination link of a website while utilizing GM_xmlhttpRequest

Picture yourself browsing a webpage called "www.yourWebsite.com" and utilizing userscripts in Tampermonkey to extract data from another site using the GM_xmlhttpRequest function. As you make requests with the GM_xmlhttpRequest function to visit "exampleWe ...

List out IP addresses in JavaScript

Is it possible to allow users to input a range of IP addresses in a specific format? 10.5.15.[22-25],10.5.16.[35-37],10.5.17.20 The desired outcome is to return an array of these IP addresses for connection checking purposes later on. 10.5.15.22 10.5.15 ...

Angular allows for easy downloading of files from a server by implementing a

I am attempting to retrieve a file from the server using REST in JAVA and pass some parameters. Although I have had success with the FileSaver.js library, it is not functioning properly in Safari 8. How can I go about downloading the file in Safari? I ha ...

Error: The property 'length' of an undefined node.js cannot be read

Currently, I am facing an issue while attempting to insert multiple data into mongoDB. The data is received from another web service in JSON format and then stored in my database. However, when I try to iterate over the collected items, I encounter a Type ...

How does ng-repeat determine the presence of duplicates within an array of objects?

angular.module("myApp",[]) .controller("myCtrl",function($scope) { $scope.persons = [{name:"teja",age:11}, {name:"Ash",age:12}, {name:"teja",age:11}]; }); In ...

What is the best way to start a jquery function within a tab that has been loaded using AJAX?

My AJAX loaded tabs are functioning correctly with the following code: <div id="tabs"> <ul> <li><a href="../about-leadership-admin-ajax/">Leadership / Admin</a></li> <li><a href="../about-sales-market ...

How can I transform an array of text into dropdown options?

Currently, while utilizing Vue and vue-bootstrap, I am facing the task of populating a dropdown menu with an array of text items retrieved from my database. The <b-form-select> component in Bootstrap requires objects of the form {value: 'some va ...

Next.js App experiences a 404 Error when attempting to access the Auth0 Endpoint "api/auth/me"

Following a tutorial, I integrated my Next.js App with Auth0 successfully. However, after logging in and out, I encountered an issue where the user object is not returned when trying to display user information on the page post-login. Both the Profile.js p ...

Refreshing the view following a model update within an AJAX call in the Backbone framework

I'm struggling with my code as I can't seem to get my view to update after a model change. var ResultLoanView = Backbone.View.extend({ id:"result", initialize: function(){ this.render(); this.on('submissionMa ...

What is the importance of having Actions and Reducers in Redux?

I am trying to grasp the reasoning behind the design of Redux. For instance, let's consider a scenario where I have a store with a list of todos. If the store is represented as an object like this: {1: todo1, 2: todo2, 3: todo3, ...}* And we enca ...

Having trouble connecting Node.js to MongoDB in a Docker container?

My Docker image building and dockerizing processes are functioning properly, but I am encountering an issue with connecting to MongoDB. When running locally without Docker, everything works fine. Here is my code: schema: clientSchema.js const mongoose = re ...