mongodb - 如何使用 Mongoose Schema 修复 GraphQL Mutation 中的构造函数错误
问题描述
在验证用户是新用户还是 MongoDB 中存在的 GraphQL 突变 Mongoose 错误时遇到很多麻烦。根据下面的代码,错误消息是“消息”:“用户不是构造函数”。
这里有一个类似的问题,我重新定义了下面的变量,给定解决方案中的每个方法,以解决具有类似错误的链接问题 - 唯一的错误变化是由于缺少构造函数,例如当我使用其他方法时,例如附加错误是“用户是不明确的”。
包含所有代码的 CodeSandbox:https ://codesandbox.io/s/apollo-server-sh19t?fontsize=14
有问题的代码是:
var userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true
},
email: {
type: String,
required: true,
trim: true
},
password: {
type: String,
required: true,
trim: true
},
avatar: {
type: String
},
joinDate: {
type: Date,
default: Date.now
},
favorites: {
type: [mongoose.Schema.Types.ObjectId],
required: true,
ref: "Post"
}
});
// compile model
var User = mongoose.model("User", userSchema);
var getUserModel = function() {
return mongoose.model("User", userSchema);
};
Mutation: {
signupUser: async (_, { username, email, password }, { User }) => {
let user = await getUserModel().findOne({ username });
if (user) {
throw new Error("Please choose another username");
}
const newUser = await new User({
username,
email,
password
}).save();
return newUser;
}
}
};
完整的错误是:
{
"errors": [
{
"message": "User is not a constructor",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"signupUser"
],
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
"exception": {
"stacktrace": [
"TypeError: User is not a constructor",
" at signupUser (/xxx/xxx/xxx/servers.js:175:29)",
" at process._tickCallback (internal/process/next_tick.js:68:7)"
]
}
}
}
],
"data": null
}
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"signupUser"
],
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
"exception": {
"stacktrace": [
"TypeError: Cannot read property 'create' of undefined",
" at signupUser (/xxxx/xxxx/xxx/servers.js:175:38)"
对此问题的任何帮助将不胜感激。
解决方案
每当您尝试将new
关键字与不是构造的内容(包括未定义的值)一起使用时,都会抛出该 TypeError 。即使您在构造函数之外定义了一个用户变量,您仍然会隐藏该变量,因为您正在解构上下文参数并以User
这种方式声明一个变量。如果您没有User
正确地将模型传递给您的上下文,则尝试从上下文中获取值将导致该值未定义。要么修复上下文,要么不要不必要地破坏它。
推荐阅读
- html - 离子选择中的字符串不会改变,除非它被点击
- ffmpeg - 当有多个drawtext目标时,如何编写函数“avfilter_graph_send_command”(ffmpeg)的*args?
- c++ - 移动语义与 const 引用
- android - 评分栏在小屏幕上无法正常工作
- javascript - SyntaxError:JSON 输入角度意外结束
- qt - 具有统一 vec3 数组的 Qt3D 着色器图
- r - 我怎样才能用这样的比例制作一个情节(-1, 13000)
- c++ - 这两个示例中“++值”之间的区别
- r - 在 Shiny 中处理存储数据的反应式列表的最佳方法
- audio - 如何使用时间戳注释标记和提取音频