const { GraphQLServer } = require('graphql-yoga');
const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/test1");
const Todo = mongoose.model('Todo',{
text: String,
complete: Boolean
});
const typeDefs = `
type Query {
hello(name: String): String!
}
type Todo{
id: ID!
text: String!
complete: Boolean!
}
type Mutation{
createTodo(text:String!): Todo
}
`
const resolvers = {
Query: {
hello: (_, { name }) => `Hello ${name || 'World'}`,
},
Mutation:{
createTodo: async (_,{ text }) => {
const todo = new Todo({text, complete: false});
await todo.save();
return todo;
}
}
};
const server = new GraphQLServer({ typeDefs, resolvers })
mongoose.connection.once("open", function() {
server.start(() => console.log('Server is running on localhost:4000'))
});
您好我是节点js和mongoDB的新手。我试图启动我的服务器,但它没有启动。每次出现这样的错误时:
(node:17896) UnhandledPromiseRejectionWarning: Unhandled promise rejection.
This error originated either by throwing
inside of an async function without a catch block, or by rejecting a promise
which was not handled with .catch(). (rejection id: 1)
(node:17896) [DEP0018] DeprecationWarning: Unhandled promise rejections are
deprecated. In the future, promise rejections that are not handled will
terminate the Node.js process with a non-zero exit code.
每次这都显示出一些承诺错误。任何人都可以帮我调试这个程序。我是初学者。我不太了解它。但根据我的理解,我只编写了正确的代码。
答案 0 :(得分:0)
您的保存功能可能会抛出一个您无法处理的箭头! 您可以通过以下方式之一解决此问题:
GraphQL自己处理promise,所以这会给你相同的结果:
createTodo: (_,{ text }) => {
const todo = new Todo({text, complete: false});
return todo.save();
}
使用try catch
可以更好地处理错误:
createTodo: async (_,{ text }) => {
const todo = new Todo({text, complete: false});
try {
await todo.save();
return todo;
} catch(err) {
\\ do something with error
console.error('error=>', err);
return null;
}
}