Using Express to request data from Mongo database and only receiving the path

I've been troubleshooting a websocket function that interacts with MongoDB to fetch some data stored in the system using 'get'.

const User = require('mongoose');
const express = require('express');
const cal = require('../../app/models/data.server.model.js');
const d = require('../../app/routes/data.server.routes.js');
const data = require('./data.server.controller');

module.exports = function(app) {
require('express-ws')(app);

app.ws('/', function (ws, req) {                                                    
    ws.on('message', function (msg) {
        console.log("Message received from client: %s", msg);
        if (msg == "Update" || msg == "update") {

            const calendar = app.route('/api/data').get();                 

            console.log(calendar);
            ws.send("fromJSON " + JSON.stringify(calendar));

        }
    });
});

};

This connects to the following function:

module.exports = function(app) {
  app.route('/api/data')
     .get(data.list)
     .post(users.requiresLogin, data.create);

That ultimately calls:

exports.list = function(req, res) {
  Data.find().sort('-created').populate('creator', 'firstName lastName fullName').exec((err, datas) => {
    if (err) {
      return res.status(400).send({
        message: getErrorMessage(err)
      });
    } else {
      res.status(200).json(datas);
    }
  });
};

The expected output is my data.

However, the variable 'calendar' only contains a JSON object with 'path' (the same as 'api/data'), 'stack' & 'methods' which are empty.

I am certain the data exists, as I can access it using AngularJS code, but I'm unsure how to retrieve it here. Any assistance would be greatly appreciated. Please let me know if any part of my explanation is unclear. Thank you in advance!

Answer №1

The issue arises from attempting to utilize an asynchronous method in the same manner as a synchronous one. When you transmit a WS message, you do not possess the data at that moment.

It might not be advisable to invoke the route handler. I recommend modifying the code as follows:


// Within your model's static methods, you can create a function that returns data
// Utilize arrow functions for ES6 compatibility. You can then use Promises 
// instead of callbacks. Note that Mongoose inherently supports Promises.
// 
getData () {
    return this
        .find()
        .sort('-created')
        .populate('creator', 'firstName lastName fullName')
        .exec();
}

Subsequently, the list method should appear similar to this:

exports.list = (req, res) => {
    Data
        .getData()
        .then(data => res.status(200).json(data))
        .catch(err => {
            res.status(400).send({
                message: getErrorMessage(err)
            });
        })
}

For handling WebSockets, you can invoke the method directly from the model:

app.ws('/', function (ws, req) {                                                    //webSocket callback function
ws.on('message', function (msg) {
    console.log("Message received from client: %s", msg);
    if (msg == "Update" || msg == "update") {

        Data
           .getData()
           .then(data => {
               console.log(data);
               ws.send("fromJSON " + JSON.stringify(calendar));
           })
           .catch(/*Handle errors here*/);

    }
});

});

Alternatively, you could directly call Data.find().sort('-created')... without encapsulating it within a separate method.

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

how to use JSON to communicate between AngularJS controller and PHP

I am facing an issue with sending multiple data from JavaScript to PHP using AngularJS. Despite my efforts, I am unable to receive any data. As a beginner in AngularJS, I have included the following JS code: var data = {"name":name, "cin":cin, "job":job}; ...

Utilizing destructuring and Object.entries for advanced formatting

I'm embarking on a new React project and facing an issue with the JSON data structure returned by my API for meetings. I attempted to utilize destructuring and Object.entries. This is what I currently have: { "meetings": [ ...

Magnify novice mistakes: Unhandled promise rejection and Ensure every child has a distinct "key" property

Currently, I am working through Amazon's Getting Started with AWS tutorial found here: https://aws.amazon.com/getting-started/hands-on/build-react-app-amplify-graphql/module-four/ After successfully building and hosting the app on git, I noticed that ...

Setting a value in Ionic 3 HTML template

Attempting to assign a value in an Ionic 3 template from the ts file while also adding css properties but encountered an issue. PROBLEM Error: Uncaught (in promise): Error: No value accessor for form control with name: 'image' Error: No va ...

The necessary data is missing in the scope of the callback function

I'm facing an issue with a callback function's variable losing its scope. Consider the following simplified array of two objects: const search = [{socket: new WebSocket('ws://live.trade/123')}, {socket: new WebSocket( ...

I am trying to locate the source of the unexpected token error

Hi there! I've encountered a syntax error in my code, specifically pointing to the closing curly bracket right above the render method. The error message indicates that it's expecting a comma, but all my curly brackets seem to have opening and cl ...

Displaying numerous Google maps on a single webpage featuring distinct collections of location markers

Currently, I am utilizing the Google Maps API to showcase two distinct Google maps on a single page. Each map comes with its own set of unique markers that are dynamically generated via Wordpress from various custom post types. While one map is successful ...

Overuse of jQuery's preventDefault() and stopPropagation() functions

A recent discussion with a coworker revealed some contrasting coding practices, mainly concerning his extensive use of the two aforementioned methods in event handlers. Every event handler he creates follows this same pattern... $('span.whatever&apos ...

Using HTML, CSS, and JavaScript, the main tab must include nested subtabs to enhance navigation and

When a user clicks on a tab, another tab should open within the main tab. Depending on the selection in the second tab, input fields should appear while others hide. Something similar to the nested tabs on expedia.com. I have experimented with the tab vie ...

What is the best way to create a time delay between two consecutive desktop screenshot captures?

screenshot-desktop is a unique npm API that captures desktop screenshots and saves them upon request. However, I encounter the need to call the function three times with a 5-second delay between each call. Since this API works on promises, the calls are e ...

Error: It seems like Material UI has updated their export structure and now `makeStyles` is no longer available in the

The export of makeStyles from @mui/material/styles has been deprecated. Despite importing from @mui/styles throughout my project, this error continues to appear. I have already tried removing the node_modules folder and reinstalled, but the issue persis ...

Use `Res.download()` to send data to the client instead of directly downloading the file

I am trying to transfer a file that has been created by my NodeJS server from the server to the client for download. Users input object data which is then stored in a database. The function responsible for creating the file will read these objects and pop ...

Unleashing the power of RollupJs: A guide to dynamically bundling modules and objects

Is there a way to dynamically bundle a module/object into my RollupJs output file? I have experimented with various options without success in achieving the desired result. Below is a brief sample project that demonstrates what I am trying to achieve. The ...

Updating a property value within a JSON object: Adjusting attributes in a JSON data format

How can I modify a specific key's value in a JSON array like the following example: input = [{"201708":10,"201709": 12, "metric":"attritionManaged"},{"201708":10,"201709": 12, "metric":"attritionUnManaged"},{"201708":10,"201709": 12, "metric":"EHC"}] ...

Creating a universal function to handle setTimeout and setInterval globally, inclusive of clearTimeout and clearInterval for all functions

Is it possible to create a universal setTimeout and setInterval function with corresponding clearTimeout and clearInterval for all functions while passing values to them? The situation is as follows: 1. More than 8 functions utilizing setInterval for act ...

Utilizing Jquery to automatically scroll to a specific div on page load by setting an

I am attempting to automatically scroll to the div specified in the URL. The URL may include one of 21 different IDs such as: url.com/test#lite1 url.com/test#lite2 url.com/test#lite3 This scrolling action should happen when the page loads (so that user ...

Guide on transforming UTC time from the server to the local time of users during a GET request

I am currently facing a challenge where I need to verify if the date of the last time an element was clicked matches the current date. Due to my server generating the current date which is 5 hours ahead of my local time, there is a discrepancy causing the ...

Making a request to the specified URL using the $http.get() method with an email parameter that is currently empty

I'm having trouble sending an HTTP GET request with the email parameter in the params section of the code below: $http.get('api/me', { params: { email: email } }); However, on the backend, I am receiving empty parameters, m ...

Adapting to more user inputs in accordance with the feedback received from the AJAX response

Two user inputs are being received: area time Utilizing this information, the available restaurants in the specified area during that particular time are displayed. In addition, all the cuisines offered by these restaurants are displayed as checkboxes. ...

What is the best way to display multiple .ejs files in a nested structure using Node.js and Express?

Is there a way to display multiple .ejs files in a nested structure? Consider the code snippet below: var mysql = require('mysql'); var ejs = require('ejs'); exports.index = function(req, res){ if (req.method=='POST'){ ...