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

Tailored design - Personalize interlocking elements

I am currently working on a custom theme and I am trying to adjust the font size of Menu items. In order to achieve this, I have identified the following elements in the tree: ul (MuiMenu-list) MuiListItem-root MuiListItemText-root If I want to modify th ...

Accessing parent directives for forms - custom form names and dynamic validation

Introduction My current task involves validating dynamically created forms within a directive. These forms are all managed and submitted separately. When the form is submitted, I need to display validation errors for each individual form without any issu ...

Utilizing React SSR to dynamically import components based on API response

I am currently working on a SSR React app using the razzle tool, with the server running on the express framework. My goal is to dynamically load React components based on the value included in an API response. My folder structure looks like this: views ...

Perform an AJAX call from the main file after inserting data using AJAX beforehand

I am in need of assistance with a question I have. On a page, an AJAX function is executed after the page finishes loading, creating a table in PHP that contains two buttons: one for changing passwords and the other for deleting. This table is then injecte ...

When the button is clicked, my goal is to increase the value of the text field by one using JavaScript

I need the functionality for each button to increment the value text field located next to it <input type="number" value="0" min="0" max="5" step="1" id="qty"/> <button onclick="buttonClick()" type="button" class="btn btn-success btn-sm" id="add" ...

How can we determine the nL and nH values using an ESC/POS command?

Looking to adjust the printer's head position using ESC / pos commands: ESC $ command sets the absolute horizontal position ESC $ nL nH Trying to figure out how to calculate the values for nL and nH? ...

When using express, it is important to note that parameters cannot be accessed directly through the request.body

How can I successfully submit a form from my angular app? var formdata={ date:$scope.myForm.date ,name:$scope.myForm.name ,mobile:$scope.myForm.phone }; $http({ method:"POST" ,url:'/forms/submit' ...

`Back and forward function of pushState in history`

After successfully implementing ajax loading on all pages of my website, I encountered a challenge with the browser's back and forward buttons. Implementing the back button was straightforward: $(window).on('popstate', function(e) { get ...

What is the most effective method for locating and modifying the initial instance of an element within a group?

In my Javascript/Typescript collection, I have the following items: [ {"order":1,"step":"abc:","status":true}, {"order":2,"step":"xyz","status":true}, {"order":3,"step":"dec","status":false}, {"order":4,"step":"pqr","status":false}, {"order":5,"step":" ...

The function SetInterval is invoked multiple times

I am currently working on developing a Tetris game and I have encountered a bug that affects the speed of the game. The issue arises when the function setInterval(move_tetris_part,interval_time); is called multiple times, resulting in an increased downward ...

A guide on implementing Google reCAPTCHA in a Nuxt.js website

Trying to implement the recaptcha-module from nuxt-community in my Nuxt project but struggling with verifying if the user has passed the check. The documentation and example provided are not clear enough for me (https://github.com/nuxt-community/recaptch ...

Changing the req.path property within an expressjs middleware

I'm currently in the process of developing a middleware that will help eliminate locale strings from the path, such as /de/about becoming /about. This project is being implemented using express. To achieve this, I initially tried out the following mid ...

Matching the scope property in AngularJS directives

I am currently working on creating a custom directive that will perform regex validation on specific input fields. The goal is for the directive to determine which regex pattern to use based on an attribute provided in the input element. Here is an exampl ...

Tips for effectively sending data using slug.js in React.js

I'm a beginner in Next.js and I'm currently working on integrating the [slug.js] page. I'm wondering how to effectively manage and retrieve data for similar blogs in the sidebar. When it comes to blog details, I have successfully utilized "g ...

Can $.ajax be used as a replacement for $(document).ready(function()?

After conducting an extensive search, I am still unable to find a clear answer to my assumption. The code I used is as follows: <?php session_start(); if (isset($_SESSION['valid_user']) && $_SESSION['from']==1) { ?> ...

Creating a feature that allows users to edit the order of items within a MySQL

I am working on a project where I need to display a table of items that can be added, deleted, and reordered by the user. Initially, I planned to store these items in a MySQL database with an order column in the table. However, I realized this method is in ...

What could be causing the mousewheel event in my code to remain active?

Whenever I try to scroll on Google Chrome, an error occurs on my website. jquery-3.3.1.min.js:2 [Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See To resolve this issue: $(document).ready(f ...

Is it necessary to have n_ if I've already set up lodash?

After some research, I came across a recommendation to install lodash. However, upon visiting the lodash website, they suggest that for NodeJS, n_ should be installed instead. Are both necessary? Is one more comprehensive than the other? Do I even need eit ...

Select the Best jQuery Package

Having a variety of packages available for selection. <div class="image-grid-item" data-search="select"> <input name="pack1" type="checkbox" style="display: none;"> </div> <div class="image-grid-item" data-search="select"> <inp ...

Guide on implementing jQuery Validation plugin with server-side validation at the form level

Does anyone have a suggestion for how to handle server-side validation errors that occur after passing the initial client-side validation on a form? $("#contact_form").validate({ submitHandler: function(form) { $.ajax({ type: 'POST', ...