UnhandledPromiseRejectionWarning:未处理的承诺拒绝。 MongoNetworkError:无法连接到服务器[localhost:27017]

时间:2019-04-02 22:45:02

标签: node.js mongodb promise graphql

尽管我对graphql还是陌生的,但我正在尝试创建一个同时包含grapgql和mongodb的node.js应用程序,以进行数据库化。

尽管我正在努力创建连接,但我正在浏览器中使用GraphQLPlayground。尽管我对这个概念不熟悉,但我遇到的错误似乎与诺言有关。

const { GraphQLServer} = require('graphql-yoga');

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/librarydb')


const Book = mongoose.model("Book", {
    author:  String,
    title: String,
    available: Boolean
});


//initialization of grapgql schema
const typeDefs = `
 type Query {
   bookDetails(title: String): String!
 }

 type Book{
     id: ID!       
    title: String!
    available: Boolean!
 }

 type Mutation{
     createBook(title: String!): Book
 }`;

    //reflects the structure of the schema
const resolvers = {
    Query: {
     bookDetails: (_, {title}) => `Book ${title || "not available"}`,
    },
    Mutation: {
        createBook: async (_, { title }) => {
            const book = new Book({ title, available: false});
            await book.save();
            return book;
        }
    }
};

const server = new GraphQLServer({typeDefs, resolvers});
mongoose.connection.once("open", function() {
    server.start(() => console.log('Connection to server created successfully'));
});

最初建立了连接,但是当我开始添加一个 mongodb到我的代码,我遇到以下错误:

(node:480) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): 
MongoNetworkError: failed to connect to server [localhost:27017] on first
 connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

(node:480) [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 个答案:

没有答案