Registry /
database / apollo-datasource-mongodb
Install & Compatibility
Where this runs
No compatibility data collected yet for this library.
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
MongoDataSource
✓ import { MongoDataSource } from 'apollo-datasource-mongodb'
✗ const MongoDataSource = require('apollo-datasource-mongodb').MongoDataSource
ESM-only; CommonJS require with .MongoDataSource property also works but preferred usage is ESM.
Users extends MongoDataSource
✓ class Users extends MongoDataSource { constructor(options) { super(options); } }
✗ class Users extends MongoDataSource { constructor(options) { this.collection = options.collection; } }
Must call super(options) to initialize internal state and DataLoader; directly setting collection will break caching.
findOneById
✓ this.findOneById(id, { ttl: 60 })
✗ this.findOneById(id, 60)
Second argument is an options object, not a number. Common mistake: passing ttl directly as second param.
Shows basic setup: extend MongoDataSource, pass collection to constructor, use findOneById with TTL, and integrate with Apollo Server 4.
import { MongoDataSource } from 'apollo-datasource-mongodb';
import { MongoClient } from 'mongodb';
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
class Users extends MongoDataSource {
async getUser(id) {
return this.findOneById(id, { ttl: 60 });
}
}
const client = new MongoClient(process.env.MONGO_URI ?? 'mongodb://localhost:27017');
await client.connect();
const server = new ApolloServer({
typeDefs: `type Query { user(id: ID!): User } type User { id: ID! name: String }`,
resolvers: {
Query: {
user: async (_, { id }, { dataSources }) => dataSources.users.getUser(id),
},
},
});
const { url } = await startStandaloneServer(server, {
context: async () => ({
dataSources: {
users: new Users({ modelOrCollection: client.db('test').collection('users') }),
},
}),
});
console.log(`🚀 Server ready at ${url}`);
Errors
Common errors & fixes
TypeError: Cannot destructure property 'modelOrCollection' of 'options' as it is undefined.
Calling new Users() without passing options object.
fixnew Users({ modelOrCollection: collection }) Error: You must pass a MongoDB collection or Mongoose model.
modelOrCollection is null or not provided.
fixEnsure modelOrCollection is a valid collection or model instance.
TypeError: this.findOneById is not a function
Data source class does not extend MongoDataSource, or super() not called.
fixclass Users extends MongoDataSource { constructor(options) { super(options); } } Error: Cannot find module 'apollo-datasource'
Missing peer dependency apollo-datasource.
fixnpm install apollo-datasource
Audit
Dependencies
apollo-datasourcerequiredRequired to extend the base DataSource class from Apollo
dataloaderrequiredUsed internally for batching and caching