如何使用猫鼬模式修复GraphQL突变中的构造函数错误

时间:2019-10-01 22:06:28

标签: mongodb mongoose graphql mongoose-schema

使用GraphQL突变Mongoose错误遇到很多麻烦,无法验证用户是MongoDB中的新用户还是现有用户。根据下面的代码,错误消息为“ message”:“用户不是构造函数”。

一个类似的问题是here,我在给该链接问题的解决方案中的每个方法中都重新定义了以下变量,并出现了类似的错误-错误的更改仅是由于缺少构造函数,例如当我使用其他方法时附加错误为“用户未定义”。

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)"

在此问题上提供的任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

每当您尝试将new关键字用于非构造的东西(包括未定义的值)时,都会引发TypeError。即使您在构造函数之外定义了User变量,您仍然shadowing是该变量,因为您正在构造上下文参数并以这种方式声明User变量。如果您没有将User模型正确地传递给上下文,则尝试从上下文中获取值将导致该值未定义。修复上下文或不要不必要地破坏上下文。