如何在没有mongodb
的情况下将graphql
与mongoose
连接起来?
答案 0 :(得分:0)
您可以使用mongodb库并将其作为参数通过graphqlexpress上的上下文传递
import { MongoClient } from 'mongodb';
import { graphqlExpress } from 'graphql-server-express';
import express from 'express';
const MONGO_URL = 'mongodb://localhost:27017/your_db';
const app = express();
const startServer = async () => {
const db = await MongoClient.connect(MONGO_URL);
const mongo = {
Links: db.collection('links'),
Users: db.collection('users')
};
const buildOptions = {
schema: your_schema,
context: { mongo },
}
app.use('/graphql', bodyParser.json(), graphqlExpress(buildOptions));
};
startServer();
通过上下文传递mongo可以在解析器上访问
Query: {
allLinks: async (root, data, { mongo: { Links } }) =>
Links.find({}).toArray(),
}
答案 1 :(得分:0)
抛出错误。
import { MongoClient } from 'mongodb';
import { graphqlExpress } from 'graphql-server-express';
import express from 'express';
const MONGO_URL = 'mongodb://localhost:27017/test';
const app = express();
const startServer = async () => {
const db = await MongoClient.connect(MONGO_URL);
const mongo = {
posts: db.collection('mern'),
};
var schema = buildSchema(`
type nodemerndata{
_id : string
lable: string
value: string
class : string
}
`);
var root = {
allLinks: async (root, data, { mongo: { posts } }) =>
posts.find({}).toArray(),
};
const buildOptions = {
schema: schema,
context: { mongo },
root:root
}
app.use('/graphql', bodyParser.json(), graphqlExpress(buildOptions));
app.listen(5000, () => console.log('Now browse to localhost:5000/graphiql'));
};
startServer();