Skip to content

Commit 9818d2e

Browse files
committed
Merge branch 'NeoTheThird-actually-use-mongoose'
2 parents 6f39f9b + fb79362 commit 9818d2e

File tree

3 files changed

+17
-19
lines changed

3 files changed

+17
-19
lines changed

README.md

+5-3
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,8 @@ class Users extends MongoDataSource {
9595
}
9696
```
9797

98+
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).
99+
98100
### Batching
99101

100102
This is the main feature, and is always enabled. Here's a full example:
@@ -145,8 +147,8 @@ class Users extends MongoDataSource {
145147

146148
updateUserName(userId, newName) {
147149
this.deleteFromCacheById(userId)
148-
return this.collection.updateOne({
149-
_id: userId
150+
return this.collection.updateOne({
151+
_id: userId
150152
}, {
151153
$set: { name: newName }
152154
})
@@ -158,7 +160,7 @@ const resolvers = {
158160
author: (post, _, { users }) => users.getUser(post.authorId)
159161
},
160162
Mutation: {
161-
changeName: (_, { userId, newName }, { users, currentUserId }) =>
163+
changeName: (_, { userId, newName }, { users, currentUserId }) =>
162164
currentUserId === userId && users.updateUserName(userId, newName)
163165
}
164166
}

src/cache.js

+10-15
Original file line numberDiff line numberDiff line change
@@ -11,24 +11,19 @@ const orderDocs = ids => docs => {
1111
return ids.map(id => idMap[id])
1212
}
1313

14-
export const createCachingMethods = ({ collection, cache }) => {
15-
const loader = new DataLoader((ids) => {
16-
const res = collection.find({
14+
export const createCachingMethods = ({ collection, model, cache }) => {
15+
const loader = new DataLoader(ids => {
16+
const filter = {
1717
_id: {
18-
$in: ids,
19-
},
20-
});
21-
22-
let promise;
23-
24-
if (isModel(collection)) {
25-
promise = res.exec();
26-
} else {
27-
promise = res.toArray();
18+
$in: ids
19+
}
2820
}
21+
const promise = model
22+
? model.find(filter).exec()
23+
: collection.find(filter).toArray()
2924

30-
return promise.then(orderDocs(ids));
31-
});
25+
return promise.then(orderDocs(ids))
26+
})
3227

3328
const cachePrefix = `mongo-${getCollection(collection).collectionName}-`
3429

src/datasource.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,8 @@ class MongoDataSource extends DataSource {
2828
this.context = context
2929

3030
const methods = createCachingMethods({
31-
collection: this.model || this.collection,
31+
collection: this.collection,
32+
model: this.model,
3233
cache: cache || new InMemoryLRUCache()
3334
})
3435

0 commit comments

Comments
 (0)