diff --git a/README.md b/README.md index 5172904..413ad9c 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,8 @@ class Users extends MongoDataSource { } ``` +If you're passing a Mongoose model rather than a collection, Mongoose will be used for data fetching. All transformations definded on that model (virtuals, plugins, etc.) will be applied to your data before caching, just like you would expect it. If you're using reference fields, you might be interested in checking out [mongoose-autopopulate](https://www.npmjs.com/package/mongoose-autopopulate). + ### Batching This is the main feature, and is always enabled. Here's a full example: @@ -144,8 +146,8 @@ class Users extends MongoDataSource { updateUserName(userId, newName) { this.deleteFromCacheById(userId) - return this.collection.updateOne({ - _id: userId + return this.collection.updateOne({ + _id: userId }, { $set: { name: newName } }) @@ -157,7 +159,7 @@ const resolvers = { author: (post, _, { users }) => users.getUser(post.authorId) }, Mutation: { - changeName: (_, { userId, newName }, { users, currentUserId }) => + changeName: (_, { userId, newName }, { users, currentUserId }) => currentUserId === userId && users.updateUserName(userId, newName) } } diff --git a/src/cache.js b/src/cache.js index eae4ea5..3efcb0a 100644 --- a/src/cache.js +++ b/src/cache.js @@ -11,13 +11,20 @@ const orderDocs = ids => docs => { return ids.map(id => idMap[id]) } -export const createCachingMethods = ({ collection, cache }) => { - const loader = new DataLoader(ids => - collection - .find({ _id: { $in: ids } }) - .toArray() - .then(orderDocs(ids)) - ) +export const createCachingMethods = ({ collection, model, cache }) => { + const loader = model + ? new DataLoader(ids => + model + .find({ _id: { $in: ids } }) + .exec() + .then(orderDocs(ids)) + ) + : new DataLoader(ids => + collection + .find({ _id: { $in: ids } }) + .toArray() + .then(orderDocs(ids)) + ) const cachePrefix = `mongo-${getCollection(collection).collectionName}-` diff --git a/src/datasource.js b/src/datasource.js index 7100531..7897c86 100644 --- a/src/datasource.js +++ b/src/datasource.js @@ -29,6 +29,7 @@ class MongoDataSource extends DataSource { const methods = createCachingMethods({ collection: this.collection, + model: this.model, cache: cache || new InMemoryLRUCache() })