skip to Main Content

I have established a successful connection to my MongoDB database, confirmed by console logs. However, when I call the updateUser function, which utilizes findOneAndUpdate from Mongoose, I encounter the following errors:

Failed to create/update user: _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

Here is my updateUser function:

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 {
    // Establish database connection
    connectToDB();
    // Update user document
    console.log(`Modelo ${User}`)
    await User.findOneAndUpdate(
      { id: userId },
      {
        username: username.toLowerCase(),
        name,
        bio,
        image,
        onboarded: true,
      },
      { upsert: true }
    );

    // Revalidate path if necessary
    if (path === "/profile/edit") {
      revalidatePath(path);
    }
  } catch (error: any) {
    // Log the error for debugging
    console.error(`Failed to create/update user: ${error.message}`);
    // Optionally, rethrow the error if you want to handle it elsewhere
    throw error;
  }
}

And here is my user model:

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;

I’m unable to figure out why findOneAndUpdate is not recognized as a function despite having defined it correctly in my model. Any insights or suggestions would be greatly appreciated. Thank you!

I tried to update a user document in my MongoDB database using Mongoose’s findOneAndUpdate method. I expected the update operation to be successful and for the user document to be updated with the new data provided.

Specifically, I expected the following steps to occur:

  1. Establish a connection to the MongoDB database.
  2. Use the findOneAndUpdate method to find the user document by its ID and update it with the new data provided.
  3. Optionally, revalidate the path if necessary.
  4. Handle any errors that may occur during the update process.

However, despite correctly establishing the database connection and defining the findOneAndUpdate method in my Mongoose model, I encountered an error indicating that findOneAndUpdate is not recognized as a function. This was unexpected, and I’m seeking assistance to resolve this issue.

2

Answers


  1. By calling findOneAndUpdate directly on User, you’re interacting with the model class, where static methods like findOneAndUpdate are defined.

        import User from "../models/User.js";  // instead of using User.model use User.js or User.ts
    
    
        const updatedUser = await User.findOneAndUpdate(  // In this way, call Mongoose static methods like findOneAndUpdate in your updateUser function
               { id: userId },
               {
                  username: username.toLowerCase(),
                  name,
                  bio, 
                  image,
                  onboarded: true,
              },
              { upsert: true }
          );
    

    This approach worked in my project, and I hope it will work on your end as well.

    Login or Signup to reply.
  2. you forgot await before connectToDB();

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search