graphql-mongodb-loader
v1.0.3
Published
This repository and the following readme files are modified from @entria/graphql-mongoose-loader to support Mongodb native drive.
Downloads
47
Readme
This repository and the following readme files are modified from @entria/graphql-mongoose-loader to support Mongodb native drive.
GraphQL Mongodb Loader
Install
npm i graphql-mongodb-loader --save
yarn add graphql-mongodb-loader
Mongoose Dataloader Batch
Add batch to your GraphQL resolvers/loaders
Create a Dataloader for it
import { mongodbLoader } from 'graphql-mongodb-loader';
export const getLoader = () => new DataLoader(ids => mongodbLoader(db.collection('User'), ids));
Connection from Mongodb Cursor
Create a connection from mongodb cursor
import { connectionFromMongoCursor } from 'graphql-mongodb-loader';
export const loadUsers = async (context: GraphQLContext, args: ConnectionArguments) => {
const where = args.search
? {
name: {
$regex: new RegExp(`^${args.search}`, 'ig'),
},
}
: {};
const users = db.collection('User').find(where, { _id: 1 }).sort({
createdAt: -1,
});
return connectionFromMongoCursor({
cursor: users,
context,
args,
loader: load,
});
};
Connection from Mongodb Aggregate
Create a connection from mongodb aggregate
import { connectionFromMongoAggregate } from 'graphql-mongodb-loader';
export const loadUsersThatHaveGroup = async (context: GraphQLContext, args: ConnectionArguments) => {
const aggregate = GroupModel.aggregate([
{
$lookup: {
from: 'User',
localField: 'users',
foreignField: '_id',
as: 'users',
},
},
{
// remove empty groups
$match: { users: { $exists: true, $ne: [] } },
},
{
// promote each user to a new document
$unwind: '$users',
},
{
$sort: {
_id: 1,
},
},
{
$replaceRoot: { newRoot: '$users' },
},
]);
return connectionFromMongoAggregate({
aggregate,
context,
args,
loader: load,
});
};