Error: The variable 'err' is undefined in the mongoose mongodb code

Every time I try to execute this code, an error pops up stating that err is undefined

Below is the code snippet causing the issue:

app.post('/tinder/cards', (req, res) => {
const dbCard = req.body;

Cards.create(dbCard, (err, data) => {
    if (err) {
        res.status(500).send(err);
    } else {
        res.status(201).send(data);
    }
});

app.get('/tinder/cards', (req, res) => {
Cards.find(err, data => {
    if (err) {
        res.status(500).send(err);
    } else {
        res.status(200).send(data);
    }
});

Here is how I defined the MongoDB schema:

import mongoose from 'mongoose';

const cardSchema = mongoose.Schema({
    name: String,
    imgUrl: String,
});


export default mongoose.model('cards', cardSchema);

Any assistance in resolving this issue would be greatly appreciated. Thank you!

Answer №1

Modification

Cards.find(err, data => 

In this section, the code is searching for the filter/query as the 1st Parameter, but the err variable is not defined, hence resulting in a ReferenceError.

Corrected snippet:

Cards.find(query, (err, data) => { // Ensure 1st Parameter is filter/query

https://mongoosejs.com/docs/api.html#model_Model.find

Model.find()

Arguments

filter «Object|ObjectId»
[projection] «Object|String|Array<String>» optional fields to return, see Query.prototype.select()
[options] «Object» optional see Query.prototype.setOptions()
[callback] «Function»

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 could be causing the custom aside or slide panel to not slide properly when using Angular Strap?

I recently tried creating a slide panel and came across the Angular Strap library. After studying the documentation, I attempted to implement the slide panel using this library. However, I encountered an issue where my side panel did not slide as demonst ...

Pass intricate JavaScript object to ASP.Net MVC function

It appears that many people have shared helpful answers on a common topic, but I am still facing difficulties in making my attempt work. The issue is similar to the one discussed here, however, I am only trying to send a single complex object instead of a ...

Having trouble getting Vue async components to function properly with Webpack's hot module replacement feature

Currently, I am attempting to asynchronously load a component. Surprisingly, it functions perfectly in the production build but encounters issues during development. During development, I utilize hot module replacement and encounter an error in the console ...

javascript the debate between inline and traditional registration

Hey there, I'm a JavaScript beginner and currently learning about inline vs. traditional registration. I've managed to get code block 1 (inline) working perfectly fine, but unfortunately, code block 2 (traditional) isn't cooperating. Can som ...

Executing a function after the completion of another

Here is my function: function functionName($results) { //do some stuff disableSave() } When this function runs, I want to call the enableSave() function. How can I achieve this? I attempted to pass the function as a callback but I am unsure wher ...

Convenient Method for Making POST Requests with the Node Request Module and Callback

Does the .post() convenience method in Javascript/Node's request module accept a callback? I'm confused why it would be throwing an error like this: var request = require('request'); request.post({url: 'https://identity.api.foo/v ...

Node.JS using Express: Issue : encountering EADDRINUSE error due to address being already in use

Currently, I am in the process of developing a CRUD API with Node.js and Express. Everything was going smoothly until today when a new error message popped up. It appears that I can only use a TCP Port once. Whenever the server is stopped and restarted, I ...

What is the solution for the error message "TypeError: app.use() is seeking a middleware function"?

I am a beginner in Node.js and have encountered an issue in my passport.js or signupLogin.js file with the error message, app.use() requires a middleware function that I am struggling to resolve. I suspect it may be related to the signupLogin route, as th ...

JavaScript - Sort an array containing mixed data types into separate arrays based on data

If I have an array such as a=[1,3,4,{roll:3},7,8,{roll:2},9], how can I split it into two arrays with the following elements: b=[1,3,4,7,8,9] c=[{roll:3},{roll:2}]. What is the best way to separate the contents of the array? ...

Issue with passing reactive property to component in Vue 3 application

I am currently working on a Vue 3 application and I am in the process of setting up a store for state management. Within this application, I have several important files that play different roles: app.vue component.vue main.js store.js These files contai ...

Enhance your website with a dynamic jQuery gallery featuring stunning zoom-in

I am currently working on a mobile website project and I'm in need of a gallery feature that allows users to zoom in on images and swipe through them using touch gestures. After some research, I haven't been able to find a suitable solution in j ...

Repeating the process of duplicating with jQuery and inserting after each clone multiple times

Attempting to showcase a dynamic form for my business partner. The aim is to add select elements when the button is clicked, but currently encountering an issue where it duplicates the template twice instead of just once. Experimented with different code ...

Angular: How to Disable Checkbox

Within my table, there is a column that consists solely of checkboxes as values. Using a for loop, I have populated all values into the table. What I have accomplished so far is that when a checkbox is enabled, a message saying "hey" appears. However, if m ...

NextJS not maintaining state for current user in Firebase

I'm working on an app utilizing firebase and nextjs. I've set up a login page, but when I try to retrieve the current user, it returns undefined. This issue began a few days ago while working in react native as well - initially, it was related to ...

The pagination functionality in the customized React Native list component is malfunctioning

In my customized list component known as TableList, there is a pagination functionality implemented. However, a peculiar behavior occurs when the user interacts with the pagination arrows. Upon clicking either the next or previous arrow for the first time ...

Sending state information through props in a Vuex environment

One of the challenges I am facing is how to make a reusable component that can display data from the store. My idea is to pass the name of the store module and property name through props, as shown below: <thingy module="module1" section=" ...

The utilization of $(this) proves to be ineffective

I've been working on getting a script to add events to a specific DIV within a class using pep.js: $( ".drag" ).pep({ start: function() { $(".drag").addClass('color'); $('.drag').next(".text").fadeIn("slow"); ...

Adding a new row to a Bootstrap table while maintaining the consistent style

Is there a way to dynamically add a new table row with different styling using jQuery? I'm facing this particular issue and need help in solving it. Below, I have included some screenshots of my code and the view for better understanding. Here is the ...

eliminating various arrays within a two-dimensional array

I need help with a web application that is designed to handle large 2D arrays. Sometimes the arrays look like this: var multiArray = [["","","",""],[1,2,3],["hello","dog","cat"],["","","",""]]; I am looking to create a function that will remove any array ...

Unable to place value into an array following the invocation of a function in Angular 9

Within an array I established, I am encountering an undefined value when I use console.log. Take a look at my component.ts below: export class OrderExceptionReportComponent implements OnInit { public sessionData: ExceptionReportSessionData[] = []; n ...