首页 > 解决方案 > 如何使用 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)"

对此问题的任何帮助将不胜感激。

标签: mongodbmongoosegraphqlmongoose-schema

解决方案


每当您尝试将new关键字与不是构造的内容(包括未定义的值)一起使用时,都会抛出该 TypeError 。即使您在构造函数之外定义了一个用户变量,您仍然会隐藏该变量,因为您正在解构上下文参数并以User这种方式声明一个变量。如果您没有User正确地将模型传递给您的上下文,则尝试从上下文中获取值将导致该值未定义。要么修复上下文,要么不要不必要地破坏它。


推荐阅读