JSON.stringify doesn't support circular structures in Loopback and mongodb, resulting in a TypeError

I have been working on implementing a remote method for loopback and have encountered an issue.

"use strict";

module.exports = function(Quote) {
  /**
   *
   * @param {Function(Error, object)} callback
   */

  Quote.random = function(callback) {
    Quote.getDataSource().connector.connect(function(err, db) {
      var collection = db.collection('Quote');
      collection.aggregate([
        {Sample: {size: 1}},
      ], function(err, data) {
        if (err) return callback(err);

        return callback(null, data);
      });
    });
  };
};

When trying to view the implementation in the loopback api explorer, I keep encountering the following error.

/Users/macuser/Documents/projects/loopback/Quotes/node_modules/mongodb/lib/utils.js:132
  throw err;
  ^
TypeError: Converting circular structure to JSON
at JSON.stringify (<anonymous>)
at stringify (/Users/macuser/Documents/projects/loopback/Quotes/node_modules/express/lib/response.js:1119:12)
at ServerResponse.json (/Users/macuser/Documents/projects/loopback/Quotes/node_modules/express/lib/response.js:260:14)
at Object.sendBodyJson [as sendBody] (/Users/macuser/Documents/projects/loopback/Quotes/node_modules/strong-remoting/lib/http-context.js:437:7)
at HttpContext.done (/Users/macuser/Documents/projects/loopback/Quotes/node_modules/strong-remoting/lib/http-context.js:578:24)
at /Users/macuser/Documents/projects/loopback/Quotes/node_modules/strong-remoting/lib/rest-adapter.js:539:11
at /Users/macuser/Documents/projects/loopback/Quotes/node_modules/async/dist/async.js:3888:9
at /Users/macuser/Documents/projects/loopback/Quotes/node_modules/async/dist/async.js:473:16
at replenish (/Users/macuser/Documents/projects/loopback/Quotes/node_modules/async/dist/async.js:1006:25)
at iterateeCallback (/Users/macuser/Documents/projects/loopback/Quotes/node_modules/async/dist/async.js:995:17)
at /Users/macuser/Documents/projects/loopback/Quotes/node_modules/async/dist/async.js:969:16
at /Users/macuser/Documents/projects/loopback/Quotes/node_modules/async/dist/async.js:3885:13
at interceptInvocationErrors (/Users/macuser/Documents/projects/loopback/Quotes/node_modules/strong-remoting/lib/remote-objects.js:724:22)
at /Users/macuser/Documents/projects/loopback/Quotes/node_modules/async/dist/async.js:473:16
at replenish (/Users/macuser/Documents/projects/loopback/Quotes/node_modules/async/dist/async.js:1006:25)
at iterateeCallback (/Users/macuser/Documents/projects/loopback/Quotes/node_modules/async/dist/async.js:995:17)
[nodemon] app crashed - waiting for file changes before starting...

Could this be related to any changes in the mongodb configuration?

Answer №1

The mongodb node driver documentation states that the aggregate function now returns an AggregationCursor starting from version 2.6, indicating a change in the aggregation functionality.

Feel free to test the provided code snippet and share the outcome with me. It worked successfully in my case.

'use strict';

module.exports = function(Quote) {
    /**
     *
     * @param {Function(Error, object)} callback
     */

    Quote.random = function(callback) {
        Quote.getDataSource().connector.connect( function (err, db)  {
            var collection = db.collection('Quote');
            var check = collection.aggregate([ {$sample: { size: 1}}]);
            check.get(function (err, data) {
                if(err) return callback(err);
                return callback(null, data);
            })
        });
    };
};

Reference link: https://github.com/strongloop/loopback-connector-mongodb/issues/434#issuecomment-396890775

Answer №2

To discover how to implement a Remote Method in loopback, please refer to the following link.

module.exports = function(Quote) {
  Quote.remoteMethod('random', {
            accepts: [{ //if required
              arg: 'filter',
              type: 'object',
              required: false
          }],
            http: {path: '/list', verb: 'get'},
          returns: [
              { type: 'array', root: true } //change as per requirement 
          ]
  });

  Quote.random(filter, callback) { 

    let quoteCollection = Quote.getDataSource().connector.collection("Quote");
    quoteCollection.aggregate([
          {Sample: {size: 1}},
        ], function(err, data) {
          if (err) return callback(err);

          return callback(null, data);
        });
    }
};

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

"SyntaxError: import statements can only be at the top level of a module" is the error message that I keep encountering.`

For the complete code, click here: https://github.com/vscodr/axios_issue After spending some time away from JavaScript working in Python, I decided to come back and try to tackle similar tasks using JS. However, I seem to be stuck at a very basic issue! D ...

Having trouble implementing express-unless to exclude specific routes from requiring authentication

Being relatively new to JavaScript and Node.js, I decided to incorporate express-jwt for authenticating most of my APIs. However, I wanted to exclude certain routes like /login and /register from authentication. After exploring the documentation for expr ...

Maximizing Input Field Utility in React JS

I have a challenge with retrieving values from the input field and passing it to the useEffect. I specifically want the search to be triggered only after pressing the onSearch function. The issue is that I can only capture the value using the onChange func ...

Is it possible that the images are unable to load on the page

The frontend code successfully retrieves the image links sent by the backend but encounters issues displaying them. Despite confirming that the imgUrl data is successfully fetched without any hotlink protection problems, the images are still not appearing ...

Unable to add ngRoute dependency in Angular

I'm facing an issue while trying to set up a basic Angular route in my current project, encountering the error: Uncaught Error: [$injector:modulerr] I have ensured that I have injected ngRoute as a dependency in my module and included the angular-rou ...

What is the process of creating a global variable in Node.js?

My task involves calling an API that will return a JSON object stored in a variable. I need to print part of this JSON object on the console. However, I am facing an issue where I can't load the data to the console outside of the request{} loop. How c ...

Generate a fresh array from the existing array and extract various properties to form a child object or sub-array

I am dealing with an array of Responses that contain multiple IDs along with different question answers. Responses = [0:{Id : 1,Name : John, QuestionId :1,Answer :8}, 1:{Id : 1,Name : John, QuestionId :2,Answer :9}, 2:{Id : 1,Name : John, QuestionId :3,An ...

Once I've located the correct document, how can I search for the object with the specific date and then modify it in mongoose?

I am currently working on creating a heatmap using react-d3-heatmap, and the data structure required for this is [{date: Date, count: Number}]. Below is the schema I have set up for this model. const HeatMapSchema = new mongoose.Schema({ user: {type: ...

Iterating through an array of MongoDB document IDs, querying each ID and then storing the results in a new array results in an empty array

Having trouble with the following code: const users = [] event.registeredUsers.forEach(userId => { User.findOne({ _id: userId }).then(user => { console.log(user) // displays a valid user users.push ...

Issue with accessing property `_meta` in Chartjs and Vue.js

I'm currently in the process of developing an application using Vue.js along with Chartjs. A persistent issue I am facing involves making an http call to a service, fetching data, parsing it, and then passing it into my Chartjs component. The problem ...

Conceal the .dropdown-backdrop from bootstrap using solely CSS styling techniques

Is there a way to hide the .dropdown-backdrop element from Bootstrap for a specific dropdown on a webpage using only CSS? I found a solution that involves Javascript, you can view it on JSFiddle here. However, I am hoping to achieve this without relying o ...

What could have occurred if you reassigned setInterval to a variable within the useEffect hook?

Can multiple setInterval functions be defined repeatedly to the same variable in a React hook useEffect? After checking, I found that the variable has a new setInterval id value every time it is defined. However, I am curious if there are any instances re ...

anychart: The right side of Gantt Charts is being cut off or trimmed

I am utilizing anychart for my user interface. My data timelines are in epoch milliseconds. When trying to create a Gantt chart, I notice that the right side is being trimmed. Can someone please assist me with this issue? https://i.sstatic.net/H6LHk.png ...

accelerating searches for wildcard text patterns

In my Postgres database, I have a table with over 8 million rows. The column I am interested in contains short text strings, usually less than 100 characters in total length. This column is defined as 'character varying(100)' and is indexed. Howe ...

Executing a function without using the eval() function

I am currently working on a JavaScript code that relies heavily on the eval function. eval(myString) The value of myString is equal to myFunc(arg), and I would like to find a way to call myFunc directly instead of using eval. Unfortunately, I have no co ...

What separates an array of objects from an array of ObjectIds in MongoDB?

Consider this schema: const personSchema = mongoose.Schema({ firstname: String, lastname: String, email: String, gender: {type: String, enum: ["Male", "Female"]} dob: Date, city: String, interests: [interests ...

When attempting to pass react-intl as an argument in a method of a React component during Jest testing, an error is thrown stating, "TypeError: intl.formatMessage is not a function."

Currently, I am in the process of unit testing my React component using Jest. Within this component, there are several methods that are called upon. As an example: export function fetchText(text, intl) => ((text !== 'NA') ? (intl.formatM ...

Utilize the RRule library in JavaScript by incorporating the rrule.min.js script

I am having trouble integrating the library https://github.com/jakubroztocil/rrule into my website. Whenever I try to do so, I encounter the error: Uncaught SyntaxError: Unexpected token { I have attempted the following: <!DOCTYPE html> <html ...

An alternative method for storing data in HTML that is more effective than using hidden fields

I'm trying to figure out if there's a more efficient method for storing data within HTML content. Currently, I have some values stored in my HTML file using hidden fields that are generated by code behind. HTML: <input type="hidden" id="hid1 ...

What is the best way to update placeholders in Angular 8+?

I have a collection of items: a = ['apple', 'mango', 'grape', 'papaya', 'banana', 'cucumber']. An input element is present with a placeholder stating select from fruits (the array elements should ...