如何使用 Mongoose Schema 修复 GraphQL Mutation 中的构造函数错误

How to fix constructor error in GraphQL Mutation with Mongoose Schema

在验证用户是新用户还是 MongoDB 中存在的 GraphQL 突变 Mongoose 错误时遇到很多麻烦。根据下面的代码,错误消息是 "message":"User is not a constructor"。

一个类似的问题是 ,我重新定义了下面的变量,给出了解决具有类似错误的链接问题的每个方法 - 错误的唯一变化是由于缺少构造函数,例如当我使用其他方法时append 之类的方法错误是 "User is undefined"。

包含所有代码的 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 变量,您仍然是 shadowing 那个变量,因为您正在解构上下文参数并以这种方式声明一个 User 变量。如果您没有正确地将 User 模型传递给您的上下文,尝试从上下文中获取值将导致该值未定义。要么修复上下文,要么不要对其进行不必要的破坏。