首页 > 解决方案 > 在通过 mergeResolvers 导入的外部解析器文件中使用 MongoDB 集合变量时的 ReferenceError

问题描述

这是一个完全简化的示例,可以更好地解释这个问题!所以当我使用解析器查询 getAllUsers时,MongoDB 集合 Users在外部解析器文件中不可用user.js。因此,当我发送该查询时,我得到:

ReferenceError:未定义用户

这是正确的行为。但我不想在我的 index.js 中包含所有解析器,因为我以这种方式有更好的模块化。所以我在这样的外部文件中有我所有的类型定义和解析器。

当前文件结构

index.js 
  /graphql
    /typdef
      user.graphql
    /resolver
      user.js

user.graphql架构正常工作。user.js正如已经说过的那样,当我使用不可用的Users变量执行查询时,这正是产生错误的原因。

这里index.jsuser.js

index.js

import express from 'express'
import cors from 'cors'
const app = express()
app.use(cors())
import bodyParser from 'body-parser'
import {graphqlExpress, graphiqlExpress} from 'graphql-server-express'
import {makeExecutableSchema} from 'graphql-tools'
import {fileLoader, mergeTypes, mergeResolvers} from 'merge-graphql-schemas';
import {writeFileSync} from 'fs'
const typeDefs = mergeTypes(fileLoader(`${__dirname}/graphql/typedef/*.graphql`), { all: true })
writeFileSync(`${__dirname}/graphql/typedef.graphql`, typeDefs)

export const start = async () => {
  try {
    const MONGO_URL = 'mongodb://localhost:27017'
    const MongoClient = require('mongodb').MongoClient;
    MongoClient.connect(MONGO_URL, function(err, client) {
      console.log("Connected successfully to server");
      const db = client.db('project');
      const Users = db.collection('user')
    });
    const URL = 'http://localhost'
    const homePath = '/graphql'
    const PORT = 3001
    app.use(
      homePath, 
      bodyParser.json(), 
      graphqlExpress({schema})
      )
    app.use(homePath, 
      graphiqlExpress({
        endpointURL: homePath
      })
    )
    app.listen(PORT, () => {
      console.log(`Visit ${URL}:${PORT}${homePath}`)
    })
  } catch (e) {
    console.log(e)
  }
}

用户.js

export default {
  Query: {
    getAllUsers: async () => {
    return (await Users.find({}).toArray()).map(prepare)
    }
  }
}

将 MongoDB 或Users集合传递给解析器文件的最佳方法是什么。或者这个问题有更好的解决方案吗?

标签: javascriptmongodbexpressgraphqlgraphql-js

解决方案


首先,这不是一个合适的解决方案,因为在外包模式时声明全局变量是一个糟糕的设计。但它成功了,也许这样有人会知道如何改进这个修复。

因此,要解决这个问题,我所要做的就是将变量从 local const 更改为 global

所以在index.js const Users = db.collection('user')中被global.Users = db.collection('user').

user.js也一样。这里return (await Users.find({}).toArray()).map(prepare)由 重写return (await global.Users.find({}).toArray()).map(prepare)


推荐阅读