The function User.find does not exist and it is not possible to replace the `users` model after it has

Currently, I am experimenting with using mongoose, mongoDB, next, and express in a test project. Despite referencing solutions like Cannot overwrite model once compiled Mongoose and others, I am encountering issues unique to my situation.

Upon initialization, an error "User.find is not a function" is displayed, followed by the error "Cannot overwrite users model once compiled" after reloading the server (e.g., saving changes).

The versions I am working with include nvm 10.18.0, next 9.3.4, express 4.17.1, mongoose 5.9.7

Below are snippets from my files:

//server.js
const express = require('express');
const next = require('next');

//...omitted for brevity

module.exports = User;

//./models/user.js
var mongoose = require('mongoose');

//...omitted for brevity

const User = mongoose.model('users', SomeModelSchema );

module.exports = User;

//./pages/index.js
const User = require('../models/user');

//...omitted for brevity

export default Home

If anyone has suggestions on how to resolve these errors, I would greatly appreciate it.

Answer №1

With the guidance of my coworkers, I have come to realize that it is not possible to utilize a model in the frontend. Instead, by creating a server-side function like the one below:

//./foo.js    
const User = require('./models/user');

const foo = () => {
    console.log(">>>>>>>>>>>>>>>>>>>>>",User.find({email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82f4e3c2efe3ebeeace1edef">[email protected]</a>'}))
}

module.exports = foo;

You can import and use it in the server as demonstrated below:

//./server.js
const foo = require('./foo')

app.prepare()
  .then(() => {
    const server = express();
    var mongoDB = 'mongodb://127.0.0.1:27017/admin';
    mongoose.connect(mongoDB);
    var db = mongoose.connection;
    foo()
...
})

This approach should work seamlessly!

I am grateful for all the assistance provided!

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 are the best plugins and projects to maximize IntelliJ IDEA's potential for JavaScript development?

I am currently in the process of developing a web application utilizing the MEAN stack: MongoDB, Express, Angular, and Node.js. The foundation of my project is built upon Daftmonk's angular-fullstack Yeoman generator. Despite my primary experience be ...

Brick-themed HTML/CSS elements drift away from each other

I'm currently designing an image collage for my website and attempted to use masonry for the layout. However, when I adjust the size of the blocks, they seem to drift apart, creating large gaps between each block. Any suggestions on how to resolve thi ...

Is there a way to verify that all CSS files have been successfully downloaded before injecting HTML with JavaScript?

I am looking to dynamically inject HTML content and CSS URLs using JavaScript. I have more than 3 CSS files that need to be downloaded before the content can be displayed on the page. Is there a way to check if the aforementioned CSS files have finished ...

Is it possible to test an Angular application using Protractor within an iframe that is hosted by a non-Angular

While trying to migrate a legacy app to Angular, we encountered an issue where the legacy app loads the new app in an iframe. Testing this integration with Protractor has proven challenging due to the fact that the legacy app is not built on Angular. If t ...

Executing a C# function from an HTML hyperlink

I am in the process of developing a website using ASP.NET C#. The site will feature a GridView with data that can be exported, such as to Excel or other formats. To handle the export functionality, I plan to utilize code from this resource. When a user c ...

Tips for swapping images as a webpage is scrolled [using HTML and JavaScript]

Hi there, I am looking to make some changes to a JavaScript code that will switch out a fixed image depending on the user's scrolling behavior. For example, when the page loads, the image should be displayed on the right side. As the user scrolls down ...

Are your GetJSON requests failing to execute properly?

I have a code snippet that executes in a certain sequence and performs as expected. <script> $.getJSON(url1, function (data1) { $.getJSON(url2, function (data2) { $.getJSON(url3, function (data3) { //manipulate data1, data2, ...

Modify the value of a variable every 250 milliseconds

Currently working on a game website and stuck at the registration stage. We are looking to allow players to input a code in their Ingame notes for verification purposes. I have created a PHP class to retrieve the ingame notes, but now I need to set a java ...

Transforming an object containing methods into a string using Javascript specifically for Photoshop

I have a unique universal object that is essential for my Photoshop scripts. It contains various properties and methods like this: var Object = {}; Object.text = "this is some text"; Object.toolbox = new ToolBox(); // specialized object with its own funct ...

Can PushState be used to Ajaxify CSS files?

Currently, I am in the process of developing a basic website and have decided to incorporate the Ajaxify library for seamless page transitions. One challenge I have encountered involves the combination of global CSS files (applied throughout the entire sit ...

Issue with nextjs not returning the updated object correctly

I'm currently developing a nextjs app that incorporates authentication. There are two key functions that I execute on each page load. The first function checks for the existence of jwt cookies and then calls another function to validate the tokens if ...

having issues with my expressjs router functionality

Embarking on my MEAN stack journey, I have been immersing myself in tutorials. It has become clear that everyone does not approach the logic in the same way. However, I find myself stuck on two particular examples. Example One: // server.js var express = ...

Can the browser doc mode be switched frequently?

My web application is built using AngularJS, but we also have a legacy web app that functions only in quirks mode and is included via an iframe on one of our pages. The challenge is to make this legacy app work within our main browser-based application, wh ...

Issue encountered with configuring Jest for NextJS using ant design and msal, resulting in error message "Cannot use import statement outside a module

Just starting out with Jest setup and I followed the Jest example based on nextjs which can be found here Here is my jest.config.js: const nextJest = require('next/jest'); const createJestConfig = nextJest({ // Providing the path to Next.js a ...

The Query.formatError message indicates that there is an issue with the 'users.email' column in the where clause of the database query

I'm having some trouble with a piece of code. Here's my signup function : exports.signup = (req, res) => { // Adding User to Database console.log("Processing func -> SignUp"); User.create({ name: req.body.name, username: req.body. ...

What is the best way to dynamically display a React Form using Next.js?

As a novice in web development, I am currently tackling a small project using next js. The task at hand involves creating a registration form for restaurants with numerous input fields, prompting me to consider splitting the form into two separate pages. O ...

I encountered a "ReferenceError: db is not defined" while trying to call a function in Express.js with MongoDB intergr

The structure of the code is as follows: var express = require('express'); var router = express.Router(); var mongo = require('mongodb').MongoClient; function getData(){ db.collection("collection_name").find({}).toArray(function (er ...

The compilation process encountered an error: TypeError - Unable to access property 'exclude' as it is undefined (awesome-typescript-loader)

After successfully converting my existing Angular 2 project into Angular 4, I encountered the following error: Module build failed: TypeError: Cannot read property 'exclude' of undefined For more details, please refer to the attached image bel ...

Mapping an array based on specific conditions

When using my photo gallery app, I faced a challenge in mapping an array of images based on the user-selected album name. The current setup works perfectly for the 'Cambodia' album where all images are correctly logged in the console after mappin ...

ng-view or controller appears to be malfunctioning

I'm currently working on a small web application using AngularJS. I have an index.html file in the main directory and three other HTML pages within the html subdirectory. login.html list.html detail.html Initially, the index.html should load the ...