What do I do when I get a "findByIdAndUpdate is not a function" error from my controller after requiring the model

I am currently developing a web application for my company that allows us to access and manage a database of customers and their information using MongoDB, Mongoose, and Express. Our company specializes in reselling used copiers/printers and offering maintenance contracts for these machines. My goal is to store each customer as a document, with their associated machines stored as separate linked documents.

For the customers and machines, I have already set up the necessary models, controllers, and routes. However, I encountered an error while attempting to delete a machine from a specific customer:

Customer.findByIdAndUpdate is not a function TypeError: Customer.findByIdAndUpdate is not a function at module.exports.deleteMachine (C:\controllers\machines.js:21:20) at C:\utils\catchAsync.js:3:9 at Layer.handle [as handle_request] (C:\node_modules\express\lib\router\layer.js:95:5) at next (C:\node_modules\express\lib\router\route.js:144:13) at module.exports.getCustomer (C:\middleware.js:15:5) at processTicksAndRejections (node:internal/process/task_queues:96:5)

The code in question is provided below:

Controller for Machines:

const Customer = require('../models/customer');
const Machine = require('../models/machine');

module.exports.deleteMachine = async (req, res) => {
const { id, machineId } = req.params;
await Customer.findByIdAndUpdate(id, { $pull: { machines: machineId } });
await Machine.findByIdAndDelete(machineId);
req.flash('success', 'Machine has been deleted');
res.redirect(`/customers/${id}`);

};

Route for Machines:

router.delete('/:machineId', getCustomer, catchAsync(machines.deleteMachine));

The "getCustomer" middleware serves the purpose of ensuring a valid customer is being requested and setting the "foundCustomer" variable for ease of use elsewhere. Despite including it for clarification, I do not believe it is causing the issue:

module.exports.getCustomer = async (req, res, next) => {
const { id } = req.params;
const customer = await Customer.findById(id).populate({ path: 'machines' });
if (!customer) {
    req.flash('error', 'Sorry, that customer cannot be found!');
    return res.redirect('/customers');
}
res.locals.foundCustomer = customer;
next();

};

In my app.js file, I have defined the relevant routes as follows:

const customerRoutes = require('./routes/customers');
const machineRoutes = require('./routes/machines');
app.use('/customers', customerRoutes);
app.use('/customers/:id/machines', machineRoutes);

While all other machine-related routes are functioning correctly, this particular route appears to be the cause of the error. Interestingly, the previous version of this application implemented the exact same code without any issues, leaving me puzzled.

Any assistance would be greatly appreciated!

Customer Model -

const customerSchema = new Schema({
customer: String,
customerID: String,
category: {
    type: String,
    enum: ['contracted', 'billable']
},
contacts: [contactSchema],
address: String,
city: String,
state: String,
zip: String,
county: String,
machines: [
    {
        type: Schema.Types.ObjectId,
        ref: 'Machine'
    }
],
notes: [noteSchema]
});

Answer №1

Oops, I made a mistake. In my coding journey, I mistakenly exported the Customer model as part of an array of exports in this manner:

const Customer = mongoose.model('Customer', customerSchema);
module.exports = {
    Customer: Customer,
    Note: Note,
    Contact: Contact
};

When trying to require the model in my Machine controller, I initially had it written like this:

const Customer = require('../models/customer');

To fix the issue, I needed to require it in a different way like so:

const { Customer } = require('../models/customer');

After implementing that change, everything started functioning correctly, and I can continue with my project without any further obstacles.

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

ExpressJS, defining routes, locating controllers, and documenting APIs

Utilizing expressJS 4.X and nodeJS 6.x In the past, I was defining my routes in this manner : /** * @api {get} /users/:userId Get a user * @apiName GetUser * @apiGroup User * * @apiParam {Integer} userId Users unique ID. * * @apiSuccess (Success 2 ...

Breaking apart a pipe-separated text and sending it through a JavaScript function

CSS: <div class="pageEdit" value="Update|1234567|CLOTHES=5678~-9876543?|5678"> <a href="https://host:controller">Update</a> </div> Trying to retrieve the data within the div and pass it into a JavaScr ...

The Typescript counterpart to PropTypes.oneOf, utilizing a pre-existing variable

While I know this question has been addressed on Stack Overflow here, I still find myself struggling with a similar issue in my TypeScript project. Currently, I am in the process of converting a JavaScript project to Typescript. Within one of my React com ...

The default value is not displayed in the Angular dropdown menu

When using regular html select menus, if you create an option element with selected and disabled attributes and provide text for that option, the text will be displayed by default in the select menu. Below is a basic example of HTML code: <select name= ...

How can I add content to the body of a modal in Bootstrap 3?

My application has a button that, when clicked, is supposed to trigger a modal popup containing some data. I want the data in the modal to come from another application via a PHP file accessed through a URL. How can this be achieved? <?php echo '& ...

Transition not influencing the scale property when activating a class

My modal is not scaling in and out properly when I toggle the 'active' class. It either fully scales out or scales in without any transition. Example: const openPopupButtons = document.querySelectorAll('[data-popup-target]'); const ...

Issue with Node.js: req.session data does not persist

Currently, I am working on integrating a login feature using express, nuxtjs, and express-session. The functionality works well without any issues until the page is refreshed. However, after refreshing the page, the session data is not retained. I have co ...

Troubleshooting lpush errors in Node.js with Redis

I'm currently developing a web application using node.js and redis. The goal is to store each incoming request in a redis queue before saving it into a database. However, I keep encountering an error whenever the program executes the lpush command. Be ...

Adjust the color of the glyphicon icon within a date and time picker dropdown component

I decided to implement the bootstrap datetimepicker using this gem and utilized the following HTML code: <div id="custom-dates" style=" clear:both;"> <div class="container"> <div class="row"> <div class='col-md-3 col-xs-3' ...

Encountered a 'Require() of ES Module' Error while Implementing Visx with Nextjs

Currently, I am utilizing the Visx library for chart creation within Nextjs. The scales provided by Visx are imported in this manner: import { scaleBand, scaleLinear, scaleOrdinal } from "@visx/scale" It is important to note that internally, Vi ...

Button cannot be activated upon selecting a row

The goal is to activate a button when a row is selected. However, the button remains disabled even after selecting a row. Below is a snippet of the code as well as a screenshot showing the issue [error_1]: onInit: function () { var oViewMode ...

leafletjs: render Points of Interest (POIs) using canvas technology

I am looking for a way to efficiently draw multiple geo points using Leaflet and HTML5 canvas. My data source is geoJSON, but according to the documentation of Leaflet, drawing geo positions as canvas is currently not supported. var anotherGeojsonLayer = ...

It appears that the u18next node setLng function is not functioning properly

I encountered an issue with the i18next module for node.js (using express). In my app.js file, I initialized the module like so: i18n.init({ ns: { namespaces: ['text'], defaultNs: 'text'}, resSetPath: 'locales/__lng__/new. ...

How come the values in my object remain inaccessible even after assigning values to it with navigator.geolocation.getCurrentPosition() and returning it?

After successfully assigning values to my pos object within the whereAmI function using navigator.geolocation.getCurrentPosition(), I can confirm that lat and lng are present inside the object. However, attempting to access these properties later on resu ...

Learn how to run javascript code using Nodejs child_process and Meteor

Is it possible to use the child_process module to execute Meteor server-side code instead of just Linux commands? I am interested in using spawn to create a separate process for running my loop. The loop involves logging a message every minute. myLoop(){ ...

Making an Ajax call to a RESTful API from another domain

My Restful API functions properly when called from Postman using a specific configuration. I provide the following details on Postman to receive a response: - POST: "" There is no need for authorization. Headers: Content-Type : application/json, username: ...

What steps should I take to fix an error in my code?

My current objective is to write a program that generates a square with dimensions of 200 pixels by 200 pixels. The square should be colored using specific RGB values: red (red value of 255), green (green value of 255), blue (blue value of 255), and magent ...

Converting a JSON PHP array into Javascript

How can I convert this PHP array named $data into JSON using json_encode? Whenever I try to do so in JavaScript by writing... var myJson = <?php echo json_encode($data) ?>; console.log(myJson); I encounter errors. I am curious about any restrictio ...

How to update a value in a JSON object using Node.js Express

Hello there, I am new to NodeJS Express and I have a question about how to change the date format in the response JSON. I would like to convert the date format from "2017-12-14T05:23:01.000Z" to "dd/mm/yyyy". Specifically, I want the date value under the k ...

Effectively encoding and decoding AJAX and JSON objects with PHP scripting

I've successfully set up a basic HTML file with a fixed JSON object. My goal is to transfer this object to a PHP file named text.php, encode it, decode it, display it in the PHP file, and then showcase it back in the HTML file. <!DOCTYPE html> ...