当我将任何代码添加到用于查询和变异MongoDB中数据的特定解析器中时,我的服务器就会不断收到未处理的promise拒绝错误。解析器的代码如图所示:
import { Coordinates, Fridge, Fridges } from '../models/Fridge';
import { Arg, Ctx, Field, InputType, Mutation, Resolver } from 'type-graphql';
import { MyContext } from '../types';
import { Users } from '../models/User';
@InputType()
class FridgeInput {
@Field()
name: string
@Field()
address: string
@Field()
description: string
@Field(() => Coordinates)
coordinates?: Coordinates
}
@Resolver()
export class FridgeResolver {
@Mutation(() => Fridge)
async createFridge (
@Arg("inputs") inputs: FridgeInput,
@Ctx() { req } : MyContext
): Promise<Fridge | undefined> {
const author = Users.findOne({_id: req.session.userId});
const {name, address, description, coordinates} = inputs;
const fridge = new Fridges({
name,
address,
description,
author,
coordinates: coordinates ? coordinates : undefined
})
try {
await fridge.save()
} catch (error) {
console.log(error)
return undefined
}
return fridge
}
}
我试着参考冰箱课上的其他课程,不确定我做得是否正确,但我无法想象这会是问题的根源。这里的代码是:
import { Field, ID, ObjectType } from "type-graphql";
import { prop, getModelForClass, Ref } from "@typegoose/typegoose";
import { User } from './User';
export class Coordinates {
lat: number
lng: number
}
@ObjectType()
export class Fridge {
@Field(() => ID, {nullable: true})
_id: string
@Field()
@prop({required: true})
name: string;
@Field()
@prop({required: true})
address: string;
@Field()
@prop({required: true})
description: string;
@Field(() => User, {nullable: true})
@prop({required: true, ref: User})
public author: Ref<User>
@Field(() => Coordinates, {nullable: true})
@prop({required: true})
cordinates?: Coordinates;
};
export const Fridges = getModelForClass(Fridge);
最后是我的服务器的代码:
*****一旦我移除FridgeResolver,错误就会消失。此外,如果我删除了FridgeResolver中的所有代码,但将其保留在ApolloServer中,它也会消失。********
import { ApolloServer } from "apollo-server-express";
import "colors";
import connectRedis from "connect-redis";
import cors from 'cors';
import express from "express";
import session from "express-session";
import Redis from "ioredis";
import mongoose from "mongoose";
import "reflect-metadata";
import { buildSchema } from "type-graphql";
import { COOKIE_NAME, __prod__ } from "./constants";
import { FridgeResolver } from './resolvers/fridge';
import { HelloResolver } from "./resolvers/hello";
import { UserResolver } from "./resolvers/user";
// create express instance:
const app = express();
// connect to our mongo database
const connectDB = async() => {
try {
const conn = await mongoose.connect('mongodb://localhost:27017/cff', {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false,
autoIndex: true
});
console.log(`Mongo Connected to: ${conn.connection.host}`.cyan.bold)
} catch (error) {
console.log(`Error: ${error}`.red.bold);
process.exit();
}
};
connectDB();
const main = async () => {
// Redis
const RedisStore = connectRedis(session);
const redis = new Redis();
// cors
app.use(cors({
origin: 'http://localhost:3000',
credentials: true,
}));
// Session middleware needs to come before apollo so we can use it inside apollo middleware
app.use(
session({
name: COOKIE_NAME,
store: new RedisStore({
client: redis,
disableTouch: true,
}),
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 365 * 10, // 10 years
httpOnly: true,
sameSite: 'lax',
secure: __prod__, // cookie only works in https
},
secret: '123',
resave: false,
saveUninitialized: false,
})
);
// Apollo server
const apolloServer = new ApolloServer({
schema: await buildSchema({
resolvers: [HelloResolver, UserResolver, FridgeResolver],
validate: false,
}),
context: ({ req, res }) => ({ req, res, redis })
})
apolloServer.applyMiddleware({ app, cors: false });
const PORT = 4000;
app.listen(PORT, ()=> {
console.log(`Server is listening on port ${PORT}`.blue.bold)
});
};
main().catch((err) => {
console.log(err.red.bold)
});
@Resolver()
export class FridgeResolver {
@Mutation(() => Fridge)
async createFridge (
@Arg("inputs") inputs: FridgeInput,
@Ctx() { req } : MyContext
): Promise<Fridge | undefined> {
const author = await Users.findOne({_id: req.session.userId}); //You are using async function so you might have to use await here.
const {name, address, description, coordinates} = inputs;
const fridge = new Fridges({
name,
address,
description,
author,
coordinates: coordinates ? coordinates : undefined
})
try {
await fridge.save()
} catch (error) {
console.log(error)
return undefined
}
return fridge
}
}
我通过将冰箱类中的字段更改为:来消除错误
import { Field, Float, ID, ObjectType } from "type-graphql";
import { prop, getModelForClass, Ref } from "@typegoose/typegoose";
import { User } from './User';
@ObjectType()
export class Fridge {
@Field(() => ID, {nullable: true})
_id: string
@Field(() => String)
@prop({required: true})
name: string;
@Field(() => String)
@prop({required: true})
address: string;
@Field(() => String)
@prop({required: true})
description: string;
@Field(() => User)
@prop({ ref: () => User})
public author: Ref<User>
@Field(() => Float, {nullable: true})
@prop()
lat?: number
@Field(() => Float, {nullable: true})
@prop()
lng?: number
};
export const Fridges = getModelForClass(Fridge);
我不完全理解这怎么会导致未经处理的拒绝承诺。如果有人有任何信息,我将不胜感激,因为我自己找不到任何信息。