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

Resolving the "Error: Cannot update a React state on an unmounted component" issue

I encountered a console error while attempting to navigate to a new page within my web application. Here's the error message I received: Warning: A React state update was attempted on an unmounted component, which is essentially a no-op. However, t ...

Using ExpressJS to generate a page with inputs

Using ExpressJS, I have created an Object of the IndexController in my router (index.js) and passed a String as a constructor argument. I then attempted to call the showDefaultFeed method. Expected output from "index.hbs" view was to print the argument pa ...

Tips for editing bootstrap-vue table columns using non-Latin characters?

I need to create a table using the Cyrillic alphabet, but the keys of the object must be in the Latin alphabet within the program. Example : export default { data() { return { wmsFields: ['№', 'Наименование', ...

Service in Angular2+ that broadcasts notifications to multiple components and aggregates results for evaluation

My objective is to develop a service that, when invoked, triggers an event and waits for subscribers to return data. Once all subscribers have responded to the event, the component that initiated the service call can proceed with their feedback. I explore ...

Can Express Handlebars be used solely for rendering a partial without including a layout?

I have successfully configured express handlebars with the following folder structure: views/ layouts/ partials/ User Search Partial HTML (located in views > partials) <div id="user-search"> <h1>Search Users</h1> </div ...

What is the process for executing PhantomJS commands through a NodeJs server?

My current challenge involves setting up a Node Server and incorporating PhantomJS commands within the NodeJS server. An example command includes: phantomjs phantom-server.js http://example.com Although I found some information related to this issue on ...

Retrieving blog posts formatted in markdown from a centralized JSON file

My current setup involves using react-markdown to load markdown content from a JSON file. I have opted for a static site hosted on CloudFront to save money and eliminate server operation costs. All posts are compiled into a posts.json file which is then ...

When using iOS, inserting an iFrame with a source URL (SRC) on a webpage will automatically open the URL

Currently facing a peculiar issue within a Cordova app, specifically on iOS. The scenario is: I have an HTML page with existing content. At a later stage, I fetch additional HTML from a remote source and inject it into the original HTML page. However, whe ...

The rating system does not accurately incorporate the values provided by the API

Incorporated the star rating package into my ReactJS code to showcase the star value retrieved from a mock API. import { Rating } from "react-simple-star-rating"; However, when attempting to make it read-only, it does become static but fails to ...

Troubleshooting partial content error while streaming MP4 with GridFS, NodeJS, and React

I have been working on my streaming project for a while now and everything seems to be going well, except for the fact that I am encountering a 206 partial content error when streaming large MP4 files. After conducting extensive research, it appears to be ...

The property 'innerHTML' cannot be assigned to null, as stated in Vue

I am dealing with two components that allow for editing JSON objects. Additionally, I have a button that toggles between these two components. Below is the HTML code snippet: <v-btn @click="switchConfigClicked">Switch config</v-btn> <h4 cla ...

Tips for resolving this unhandled error in React TypeScript

After creating a program in React TypeScript, I encountered an uncaught error. Despite running and debugging tests and conducting extensive research on Google, I have been unable to resolve this issue on my own. Therefore, I am reaching out for assistance ...

Using jQuery .css({}) is not causing negative margin to function as expected

$('#thankYouMessage').css({"height": textHeight, "margin-top:": "-52px", "padding-left": "19px"}); The CSS property 'padding-left:' will be applied as expected, but the negative margin will not take effect. The 'margin-top:' ...

An easy guide to rerouting a 404 path back to the Home page using Vue Router in Vue.js 3

Hello amazing community! I'm facing a small challenge with Vue.js 3. I am having trouble setting up a redirect for any unknown route to "/" in the router. const routes = [ { path: "/", name: "Home", component: Home, }, { path: "* ...

Obtain information from express middleware

I am currently working on a project using node.js. As part of my application, I have developed a middleware function that is triggered whenever a GET request is made. This occurs when someone visits the home page, profile page, or any other page within my ...

Is it advisable to refrain from handling all routes in a Node/Express application using an asterisk?

Recently, I set up a simple node app that captures all incoming requests: app.get('*', function(req, res) { //handle GET request with specific parameter } I'm wondering if there are any drawbacks to using this catchall method if the app ...

What is the functionality behind app.listen() and app.get() in Hapi.js, Restify, and Koa?

Using the http node module, which consists of only native modules, how can I create a custom version of app.listen() and app.get() by utilizing the http module with a constructor? var app = function(opts) { this.token= opts.token } app.prototype ...

Sending data from an AJAX request to a Spring controller is a common task in web

var TableDatatablesEditable = function () { var handleTable = function () { function restoreRow(oTable, nRow) { var aData = oTable.fnGetData(nRow); var jqTds = $('>td', nRow); for (var i = 0, ...

Node.js communicates using commas instead of newlines

Whenever I use Express to generate a project, it outputs commas instead of newlines. For example: express my_project This generates everything in a single line ,/**, * Module dependencies., */,,var express = require('express'), , routes = ...

Is it possible for the original object to be altered when passing it as a parameter to a function in a different file?

When you update an object passed as a parameter, will the updates be reflected "upwards" if the method receiving the parameter is in a different file? Or will the object retain its own context despite being passed down? ...