【问题标题】:How to fix constructor error in GraphQL Mutation with Mongoose Schema [duplicate]如何使用 Mongoose Schema 修复 GraphQL Mutation 中的构造函数错误 [重复]
【发布时间】:2020-01-31 05:19:59
【问题描述】:

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

一个类似的问题是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)"

对于这个问题的任何帮助将不胜感激。

【问题讨论】:

  • 已经有许多类似的问题(hereherehere)归结为相同的根本原因——试图使用未定义的值作为构造函数,所以我把这个问题当作一个骗子来结束。您可以在下面看到更详细的说明。

标签: mongodb mongoose graphql mongoose-schema


【解决方案1】:

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

【讨论】:

  • 我不明白你写了什么,但感谢您的输入。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-06
  • 2017-03-09
  • 2014-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多