issue with callback - callback is not a valid function

I encountered an error stating: uncaughtException TypeError: cb is not a function I suspect that this error is related to a callback issue, but I am unsure of the root cause.

app.put('/badge/student_badge/:id', upload, (req, res, next) => {
  const name = req.body.name;
  let data = {
    name: name
  }
  badger.updatePersonBadge({
    id: req.params.id
  }, data, (err) => {
    if (err) return next(err);
    res.status(201).json({
      message: 'Post updated successfully!'
    });
  });
});

function updatePersonBadge(options, cb) {
  schemas.badger.then(b => {
    b.findById({
      _id: options.id
    }, (err, resp) => {
      if (err) return cb(err);
      if (!resp) return cb("no badge found");
      name = options.name;
      title = resp.title;
      points = resp.points;

      updateBadge(name, title, points, cb);
      cb(null, resp);
    })
  })
}

function updateBadge(name, title, points, cb) {
  const dateCreated = new Date(),
    dateUpdated = dateCreated;
  registerSchemas.personModel.then(p => {
    p.findOneAndUpdate({
      name: name
    }, {
      $push: {
        badges: [{
          title: title,
          points: points,
          dateCreated: dateCreated,
          dateUpdated: dateUpdated
        }]
      }
    }, (err, resp) => {
      if (err) return cb(err);
      if (!resp) return cb("no person found");
    })
  })
}

Answer №1

Failure to include the cb argument in your function is causing issues, especially if it is meant to be optional. Without an if statement to handle this scenario, the function will not behave as expected:

updatePersonBadge(options, cb) {   // << Expecting cb (callback) argument

  // ...
  cb(null, resp);    // Since cb is being called, it is not optional (It is required)

If you are calling the function like updatePersonBadge(aaa) instead of

updatePersonBadge(aaa, myCallbackFn)
, the cb() variable will be undefined, even though it is written as a function call that does not exist.

To make the callback function optional, consider the following approach:

  //...
  if(cb) cb(null, resp); // Invoke the cb function only if cb exists

Or for a more specific check:

  //...
  if(cb && typeof cb === 'function') cb(null, resp);

In one instance instead of passing a function, you are passing data:

badger.updatePersonBadge({}, data, errFn);

Answer №2

It seems like this is the exact location where you trigger the updatePersonBadge function. If so, ensure that you are passing the callback as the third argument and make sure to utilize them correctly.

badger.updatePersonBadge(
{
   id: req.params.id
}, 
data,
(err) => {
    if (err) return next(err);
    res.status(201).json({
       message: 'Post updated successfully!'
    });
});

Answer №3

The issue in this scenario lies in a parameter mismatch - instead of passing a callback, data is being sent in its place.

app.put('/badge/student_badge/:id', upload, (req, res, next) => {
const name = req.body.name;     
let data = {
    name: name
}
badger.updatePersonBadge({id:req.params.id}, data, (err)=>{.   -- three arguments passed
    if (err) return next(err);
    res.status(201).json({
        message: 'Post updated successfully!'
    });
});

});

In the function definition, only 2 parameters are specified when it should have 3. It is important to validate this particular scenario.

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

Tailwind CSS compilation failure | Unexpected token found at 26:33 in Acorn

While attempting to implement tailwindcss using default CSS, an unexpected issue arose... tailwindcss 2.0.2 ? Building from default CSS... (No input file provided) ? SyntaxError: Unexpected token (26:33) at _class.pp$4.raise (C:\xampp& ...

Detecting a single click versus a drag using RxJS

Currently, I am working with an AngularJS component that needs to respond to both single clicks and drags for resizing purposes. To tackle this problem, I have integrated RxJS (ReactiveX) into my application in search of a suitable solution. The Angular as ...

Is there a way to transfer a user-uploaded image to a different div by clicking a button?

In my code, the first div displays an image, the second div allows for uploading an image, and the third div shows a preview. I am looking to update the first div with the uploaded image once a button is pressed. <html> <body> <div id= ...

Configuring a devServer proxy leads to a 404 error

Within my src/vue.config.js file, I have the following configuration: module.exports = { devServer: { proxy: { '/api': { target: 'http://localhost:8081', changeOrigin: true, }, }, }, }; When I c ...

Issue: [$injector:unpr] The provider "someProvider" is not recognized by the system and is causing an error

When using angularjs I made sure to register a service in the services directory under modules -> module_name angular.module('module_name').factory('service_name', [ function() { // Public API console.log('hell ...

My webpage effortlessly retrieved data without the need to manually click a button using JavaScript, and a subsequent button call was made

Could someone assist me with this issue? I am utilizing the fetch API and have it linked to a button. The problem I am facing is that even without clicking the button, my data is being fetched from the API. When I click the button to fetch data for the fir ...

Turn off wss for ASP.NET Core Hot Reload functionality

Currently, I am utilizing ASP.NET Core's hot reload functionality. It attempts to establish connections with two websockets: ws and wss. The ws connection is successful and enables hot reload to function properly. However, since my local development ...

Resetting the form and validation in AngularJS post form submission

I need help resetting a form and all validation messages after submission. Check out my code on plunker: http://plnkr.co/edit/992RP8gemIjgc3KxzLvQ?p=preview Here is the code snippet: Controller: app.controller('MainCtrl', function($scope) { ...

Step-by-step guide to sending RESTful requests using Angular's $http service

Currently, I am working with Nodejs and my route has this structure: router.get("/profil/:id",function (req,res) { }); I am looking to push data from my angular controller using the $http service. ...

Retrieve the content of the specified element within the webpage

How can I modify the method to successfully retrieve the text content of an element on a webpage using Selenium with JavaScript? Currently, it is returning undefined. homepage.js const { Builder, By, Key, until } = require('selenium-webdriver'); ...

The function is not explicitly declared within the instance, yet it is being cited during the rendering process in a .vue

import PageNav from '@/components/PageNav.vue'; import PageFooter from '@/components/PageFooter.vue'; export default { name: 'Groups', components: { PageNav, PageFooter, }, data() { return { groups: ...

Switch the glyphicon based on the open/closed state of the collapsible element - Bootstrap

Is there a way to update the glyphicon based on whether or not a collapsible element is open? This is the code I currently have: <div class="jumbotron ref" data-toggle="collapse" data-target="#collapse"> <div class="row"> <div class=" ...

Creating a Prismoid Shape Using Three.js

Currently, I am utilizing Three.js and my objective is to construct a pyramid shape with its apex removed. The base of the pyramid should be a rectangle instead of a square, while the top should also be a rectangle, but not in equal proportions. Here is a ...

Utilizing express-session and SQL: Is it possible to utilize connect-session-sequelize data to populate a login/logout tracking table?

Currently, I am working on a small project that manages user login/logout using express-session and connect-session-sequelize. It is functioning correctly, but I now have the need to track the amount of time users spend on the site. Initially, my plan was ...

MongoDB Error: The user does not have permission to perform the action [find] on the collection [test.users]

Currently, my database is MongoDB Atlas and I am using Mongoose for the Node.Js/MongoDB backend. The Express server has been successfully connected to MongoDB Atlas. However, when attempting to make a Put call to the database, an error pops up: UnhandledP ...

What steps should I take to resolve the issue of "Uncaught Error: [News] is not a <Route> component. All components within <Routes> should be either a <Route> or <React.Fragment>"?

I'm having trouble with version 6 of react-router-dom while trying to create a news app. Can anyone help me with fixing it? When I use the following code, I encounter this error: Uncaught Error: [News] is not a component. All component children of ...

Investigating the delay in tap inputs on iPhones using Meteor.js and

This may not be a specific question related to Meteor.js, but I'll give it a shot: I have developed a demo at . When trying the demo on a desktop browser (specifically Chrome on Mac), it functions smoothly, with input from buttons instantly reflected ...

Enhance your HTML rendering with Vue.js directives

Check out this cool code example I created. It's a simple tabs system built using Vue.js. Every tab pulls its content from an array like this: var tabs = [ { title: "Pictures", content: "Pictures content" }, { title: "Music", c ...

Is there a way to remove specific elements from an array without using jQuery?

I've recently started diving into Javascript, experimenting with Tampermonkey scripts for the past week. The webpage I'm currently working on features dynamic elements that appear randomly with each page load. Sometimes only one element like "he ...

What is the best way to retrieve the value or text from a dropdown menu that has been added to a table row using JQuery?

Within my dynamic table, users can click an "add" button to generate a new row in the table using JQuery. One of the columns in each new row includes a dropdown box with predefined values. How can I retrieve the selected value from this dynamically created ...