【问题标题】:'Cannot overwrite `User` model once compiled.' using typescript, mongoose and lambda function“一旦编译,就无法覆盖‘用户’模型。”使用 typescript、mongoose 和 lambda 函数
【发布时间】:2020-10-16 07:47:24
【问题描述】:

我很确定由于我导入和导出 mongoose 模式的方式而出现此错误,并且我已经在 Node 中完成了此操作,但是尝试将我的代码转换为 TypeScript 给了我一些成长的痛苦。

初始运行完全正常,我得到了我正在寻找的 GraphQL 操场。但是,如果我稍微修改我的代码库,我就会在标题中看到错误。

模型\User.ts

import { Schema, Document, Model, model } from 'mongoose';

export interface IUser extends Document {
    name: string;
    email: string;
    password: string;
}

//Create Schema
const UserSchema: Schema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    }
});

export const User: Model<IUser> = model<IUser>('User', UserSchema);

模型\index.ts


import { User } from "./User";

export default {
    User
};

lambda\graphql.ts

import { ApolloServer, AuthenticationError } from "apollo-server-lambda";
import "reflect-metadata";
import resolvers from "../resolvers";
import schemas from "../schema";
import * as mongoose from "mongoose";
import { verify } from "jsonwebtoken";
import models from "../models";
import { MONGODB_URI, SECRET } from "../utils/constants";

export interface IToken extends Document {
  name: string;
  email: string;
  password: string;
}

//validate jwt then set me in graphql server context
const getMe = async (token: any) => {

  if (token) {
    try {
      const user = await verify(token, SECRET)
      return user;
    } catch (e) {
      throw new AuthenticationError("Your Session expired. Sign in again.");
    }
  }
  return null;
};


const server = new ApolloServer({
  typeDefs: schemas,
  resolvers,
  context: async ({ event }) => {
    const user = await getMe(event.headers.authorization);
    return {
      models,
      me: user,
      secret: SECRET
    }
  }
});

mongoose
  .connect(MONGODB_URI, { 'useUnifiedTopology': true, 'useNewUrlParser': true })
  .then(() => {
    console.log("mongodb connected");
  })
  .catch(err => {
    console.log(err);
  });

exports.handler = server.createHandler({
  cors: {
    origin: "*",
    credentials: true
  }
});

我怀疑这是我在 models\index.ts 中导入的方式?我错过了什么?

【问题讨论】:

  • 您是否使用了 mannieschumpert 建议的解决方案,或者您是否找到了解决此问题的其他方法?

标签: typescript mongoose lambda


【解决方案1】:

这是一个很晚的响应,但这并不难解决。在您的导出语句中,您必须检查现有模型,然后导出该模型或按定义导出模型。

这是非键入方式:

export const User = mongoose.models.User || mongoose.model('User', UserSchema);

【讨论】:

  • 嘿@mannieschumpert 你能解释一下为什么会发生这种情况以及你是如何找到这个解决方案的吗?
猜你喜欢
  • 1970-01-01
  • 2019-08-31
  • 2021-07-06
  • 2013-10-03
  • 2013-01-16
  • 2021-03-01
  • 2015-04-25
  • 2017-01-23
相关资源
最近更新 更多