将 GraphQL 与 MongoDB 连接时为空
Posted
技术标签:
【中文标题】将 GraphQL 与 MongoDB 连接时为空【英文标题】:Null when connect GraphQL with MongoDB 【发布时间】:2018-12-11 18:09:57 【问题描述】:我将 GraphQL 与 MongoDB 连接,但结果是 null
。帮我 !
index.js 文件:
const graphql = require('graphql');
const MongoClient = require('mongodb');
const assert = require('assert');
const readline = require('readline');
const mySchema = require('./schema/main.js');
const rli = readline.createInterface(
input: process.stdin,
output: process.stdout
);
const MONGO_URL = 'mongodb://127.0.0.1:27017/test';
MongoClient.connect(MONGO_URL, useNewUrlParser: true , (err, db) =>
assert.equal(null, err);
console.log('Connected to MongoDB server');
rli.question('Client Request: ', inputQuery =>
graphql(mySchema, inputQuery, , db ).then(result =>
console.log('Server Answer: ', result.data);
db.close(() => rli.close());
);
);
);
main.js 文件:
const
GraphQLSchema,
GraphQLObjectType,
GraphQLInt
= require('graphql');
const queryType = new GraphQLObjectType(
name: 'RootQuery',
fields:
usersCount:
type: GraphQLInt,
resolve: (_, args, db ) => db.collection('users').count()
);
const mySchema = new GraphQLSchema(
query: queryType
);
module.exports = mySchema;
这是结果:
Connected to MongoDB server
Client Request: usersCount
Server Answer: usersCount: null
【问题讨论】:
【参考方案1】:据我所知,您从MongoClient
连接回调获得的db
对象不是您的db
对象,而是client
对象,所以
你应该先打电话
const db = client.db
见Connect to MongoDB
如果您可以调试代码,您可以轻松找到并修复它
【讨论】:
以上是关于将 GraphQL 与 MongoDB 连接时为空的主要内容,如果未能解决你的问题,请参考以下文章
将 apollo 服务器与 mongodb mongoose 连接
.NET Core 3.1 + GraphQL + MongoDB