我已成功建立了与 MongoDB 数据库的连接,并由控制台日志确认。但是,当我调用 updateUser 函数(该函数利用 Mongoose 中的 findOneAndUpdate)时,我遇到以下错误:
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
这是我的 updateUser 函数:
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;
}
}
这是我的用户模型:
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;
我无法弄清楚为什么 findOneAndUpdate 没有被识别为函数,尽管在我的模型中正确定义了它。任何见解或建议将不胜感激。谢谢!
我尝试使用 Mongoose 的 findOneAndUpdate 方法更新 MongoDB 数据库中的用户文档。我预计更新操作会成功,并且用户文档将使用提供的新数据进行更新。
具体来说,我预计会发生以下步骤:
findOneAndUpdate
方法通过 ID 查找用户文档并使用提供的新数据更新它。但是,尽管在我的 Mongoose 模型中正确建立了数据库连接并定义了
findOneAndUpdate
方法,但我遇到了错误,表明 findOneAndUpdate
未被识别为函数。这是出乎意料的,我正在寻求帮助来解决这个问题。
通过直接在
findOneAndUpdate
上调用 User
,您可以与模型类进行交互,其中定义了 findOneAndUpdate
等静态方法。
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 }
);
这种方法在我的项目中有效,我希望它也适用于您。