​Troubleshooting findOneAndUpdate in Next.js without using instances of the class - still no success

After successfully connecting to my MongoDB database and logging the confirmation, I attempted to use the updateUser function that incorporates findOneAndUpdate from Mongoose. Unfortunately, I ran into the following errors:

Error: _models_user_model__WEBPACK_IMPORTED_MODULE_1__.default.findOneAndUpdate is not a function
TypeError: _models_user_model__WEBPACK_IMPORTED_MODULE_1__.default.findOneAndUpdate is not a function

The updateUser function I used looks like this:

import { revalidatePath } from "next/cache";
import User from "../models/user.model";
import { connectToDB } from "../mongoose";

interface Params {
  userId: string;
  username: string;
  name: string;
  bio: string;
  image: string;
  path: string;
}

export async function updateUser({
  userId,
  username,
  name,
  bio,
  image,
  path,
}: Params): Promise<void> {
  try {
    // Establishing connection to the database
    await connectToDB();
   
    console.log(`Modelo ${User}`)
    await User.findOneAndUpdate(
      { id: userId },
      {
        username: username.toLowerCase(),
        name,
        bio,
        image,
        onboarded: true,
      },
      { upsert: true }
    );

    // Path revalidation if needed
    if (path === "/profile/edit") {
      revalidatePath(path);
    }
  } catch (error: any) {
    
    console.error(`Failed to create/update user: ${error.message}`);
 
    throw error;
  }
}

This is how my user model is defined:

import mongoose from "mongoose";

const userSchema = new mongoose.Schema({
  id: {
    type: String,
    required: true,
  },
  username: {
    type: String,
    unique: true,
    required: true,
  },
  name: {
    type: String,
    required: true,
  },
  image: String,
  bio: String,
  threads: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Thread",
    },
  ],
  onboarded: {
    type: Boolean,
    default: false,
  },
  communities: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Community",
    },
  ],
});

const User = mongoose.models?.User || mongoose.model('User', userSchema);
export default User;

This is my mongoose.ts file:

"use server"
import mongoose from "mongoose";

let isConnected = false; 

export const connectToDB = async () => {

  if (!process.env.NEXT_PUBLIC_MONGODB_URL) return console.log("Missing MongoDB URL");

  if (isConnected) {
    console.log("MongoDB connection already established");
    return;
  }

  try {
    await mongoose.connect(process.env.NEXT_PUBLIC_MONGODB_URL);
    mongoose.set('strictQuery', false);

    isConnected = true; 
    console.log("MongoDB connected");
    console.log(mongoose.models);

  } catch (error) {
    console.log(error);
  }
};

Despite setting up the database connection correctly and defining the findOneAndUpdate method in my Mongoose model, I am puzzled as to why it's not recognized as a function. Any help or suggestions would be greatly appreciated. Thank you!

My attempt to update a user document using Mongoose's findOneAndUpdate method was met with unexpected issues. The operation did not proceed as anticipated, leaving me seeking assistance in resolving this matter.

  1. Establish a connection to the MongoDB database.
  2. Use the findOneAndUpdate method to locate the user document by its ID and apply the necessary updates.
  3. If required, validate the provided path.
  4. Effectively manage any encountered errors during the updating process.

Despite having executed the steps properly for establishing the database connection and configuring the findOneAndUpdate method in my Mongoose model, encountering an error suggesting that it is not recognized as a function was unexpected. Assistance with addressing this issue would be highly valued.

Answer №1

When you use the findOneAndUpdate method directly on the User model, you are interacting with the model class itself. This is where static methods like findOneAndUpdate are defined.

    import User from "../models/User.js";  // Instead of using User.model, consider using User.js or User.ts

    const updatedUser = await User.findOneAndUpdate(  
           { id: userId },
           {
              username: username.toLowerCase(),
              name,
              bio, 
              image,
              onboarded: true,
          },
          { upsert: true }
      );

This approach proved successful in my project, and I am confident it will work for you too.

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

Activate the function only once the display has finished rendering all items from ng-repeat, not just when ng-repeat reaches its last index

Currently, I am generating a list using ng-repeat and each iteration is rendering a component tag with a unique id based on the $index value. The implementation looks like this: <div ng-if="$ctrl.myArr.length > 0" ng-repeat="obj in $ctrl.myArr"> ...

Comparing MongoDB and CRUD operations in Spring Boot

Here is my pom.xml file <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="ht ...

Create a unique JSON format using customized maps

My goal is to generate a JSON format as shown below: Desired outcome: { "id": "1", "author": "firas", "templatename": "view", "typetemp": "factsheet", "structure": [ { "nb_columns": 6, "title_linechart": "product ...

Storing basic input values for a function

I am currently working on developing a versatile method that is capable of accepting any number of parameters, while storing the input type for future use. Let's take a look at an example: const customizedFunction = <A extends any[]>(innerFunct ...

Error: Couldn't locate Next.js - TypeScript module

I encountered an error with the image, but I am unsure of the reason behind it. Additionally, the directory is included in the second image. import Link from 'next/link'; import { useState } from 'react'; import { ProductModel } from ...

The property is not found in the '{}' type but is necessary in the type... Typescript connect strategy

Hello, I am currently trying to establish a connection pattern for React with TypeScript. I have a reducer set up as follows: type State = { version: number, a?: string } interface ActionC { type: string payload?: number } type IAction = Action ...

What could be the missing piece? The function is expected to provide a return value

Currently, I am developing a Typescript Express API and encountering an issue with one of my methods. The problem arises when trying to handle data received in a callback function. public async getAll(): Promise<GeneralResponse> { locationsRe ...

Angular - Enhancing the page with valuable information

Recently, I've been developing an Angular application that is designed to function as a digital magazine. This app will feature articles, news, reviews, and more. Along with this functionality, I am looking to include an admin panel where I can easily ...

Using Next.js: How to handle redirects in getServerSideProps without using res.redirect method

Currently, I am utilizing next-connect to implement some express middleware in my next.js application. When attempting to add csrf middleware, I ran into the following issue: res.redirect is not a function This error specifically pops up when I applied th ...

Using typescript with Ramda's filter and prop functions can lead to unexpected errors

I'm new to TypeScript and currently facing the challenge of converting JavaScript functions that use Ramda library into TypeScript functions. The lack of clear TypeScript usage in the Ramda documentation is making this task quite difficult for me. Sp ...

Executing a function in the view/template with Angular 2+

Whenever a function is called in the view of an Angular component, it seems to be executed repeatedly. A typical example of this scenario can be seen below: nightclub.component.ts import { Component } from '@angular/core'; @Component({ selec ...

Tips for disentangling code from types in Typescript

Instead of intertwining code and types like the example below: const compar8 : boolean | error = (action: string, n: number) => { switch(action) { case 'greater': return n > 8; case 'less': ...

The function within filereader.onload is not running properly in JavaScript

When working with FileReader to read a file and convert it to base64 for further actions, I encountered an issue. Although I was able to successfully read the file and obtain its base64 representation, I faced difficulties in utilizing this data to trigger ...

Having trouble retrieving a Dictionary item with MongoDB C# 2.0 Drivers

Having a dictionary property in my class has brought up some issues for me. [DataMember] [BsonElement("QueriableParameters")] public Dictionary<string, string> QueriableParameters { get; set; } While utilizing th ...

Sending data from view to controller in Angular using TypeScript

I am currently working with AngularJS and TypeScript, and I have encountered an issue with passing a parameter from the view to the controller. In my attempts to solve this problem, I have utilized ng-init as follows: <div class="col-md-9" ng-controlle ...

Updating the style of different input elements using Angular's dynamic CSS properties

I am seeking guidance on the proper method for achieving a specific functionality. I have a set of buttons, and I would like the opacity of a button to increase when it is pressed. Here is the approach I have taken so far, but I have doubts about its eff ...

Is it possible for changes made to an object in a child component to be reflected in the parent component

When passing an object to the child component using , how can we ensure that changes made to a specific property in the object within the child component are visible in the parent component? In my understanding, changes would not be reflected if we were p ...

How can jsPDF be used with Angular2 in Typescript?

Recently, I developed an Angular2 application that is capable of generating JSON data. My main goal was to store this JSON output into a file, specifically a PDF file. This project was built using Typescript. To achieve the functionality of writing JSON d ...

Please refrain from displaying slider images using react with react-slick

I've been working on a new .js project and decided to incorporate react-slick for the carousel feature. After installing both the react-slick and slick-carousel packages, I implemented the necessary CSS for the carousel: import React from "react& ...

Exploring hover-effects in Next JS

I am currently facing a challenge while trying to utilize the npm package hover-effect within a functional component. Despite my previous experience with similar packages in create-react-app, I am relatively new to next.js. Below is an example of how the p ...