将Localhost MongoDb连接到应用程序

时间:2017-12-28 12:25:29

标签: javascript mongodb express

我正在尝试使用React,GraphQL应用程序设置localhost MongoDB连接。一切都是根据我的知识设置和工作。我有Compass安装,用于直观地查看我的MongoDB Dbs。

Server.js文件如下所示:

const express = require('express');
const models = require('./models');
const expressGraphQL = require('express-graphql');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const schema = require('./schema/schema');

const app = express();

//--- I added the localhost MongoDb link below ---//

const MONGO_URI = 'mongodb://localhost:27017/graphql01/';
if (!MONGO_URI) {
  throw new Error('You must provide a MongoLab URI');
}

mongoose.Promise = global.Promise;
mongoose.connect(MONGO_URI);
mongoose.connection
    .once('open', () => console.log('Connected to MongoLab instance.'))
    .on('error', error => console.log('Error connecting to MongoLab:', error));

app.use(bodyParser.json());
app.use('/graphql', expressGraphQL({
  schema,
  graphiql: true
}));

const webpackMiddleware = require('webpack-dev-middleware');
const webpack = require('webpack');
const webpackConfig = require('../webpack.config.js');
app.use(webpackMiddleware(webpack(webpackConfig)));

module.exports = app;

我可以验证mongod服务在系统上正常运行。我可以通过Compass连接到文件中的上述地址。当我运行npm initialisation命令时,应用程序加载正常。但是,当我使用GraphiQL接口运行变异命令时,我最终得到错误: TypeError: Failed to fetch

如果我在这里缺少一些信息,请告诉我。

1 个答案:

答案 0 :(得分:0)

我走在正确的轨道上,应该是:

const MONGO_URI ='mongodb:// localhost:27017 / graphql01';

IE:用mongodb&替换http最后没有正斜线。