Skip to content

Commit aea6860

Browse files
authored
Merge pull request #6 from emilmork/supporting-mongoose
Supporting mongoose
2 parents 8dab732 + 980a7ba commit aea6860

File tree

2 files changed

+40
-10
lines changed

2 files changed

+40
-10
lines changed

README.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ This package uses [DataLoader](https://github.com/graphql/dataloader) for batchi
2020
- [Basic](#basic)
2121
- [Batching](#batching)
2222
- [Caching](#caching)
23+
- [Mongoose](#mongoose)
2324
- [API](#api)
2425
- [findOneById](#findonebyid)
2526
- [findManyByIds](#findmanybyids)
@@ -87,6 +88,26 @@ class Users extends MongoDataSource {
8788
}
8889
```
8990

91+
### Mongoose
92+
93+
You can use mongoose the same way as with the native mongodb client
94+
95+
```js
96+
import mongoose from 'mongoose'
97+
import Users from './data-sources/Users.js'
98+
99+
const userSchema = new mongoose.Schema({ name: 'string'});
100+
const UsersModel = mongoose.model('users', userSchema);
101+
102+
const server = new ApolloServer({
103+
typeDefs,
104+
resolvers,
105+
dataSources: () => ({
106+
db: new Users({ users: UsersModel })
107+
})
108+
})
109+
```
110+
90111
### Batching
91112

92113
This is the main feature, and is always enabled. Here's a full example:

src/cache.js

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,26 @@
11
import DataLoader from 'dataloader'
22

3+
const remapDocs = (docs, ids) => {
4+
const idMap = {}
5+
docs.forEach(doc => {
6+
idMap[doc._id] = doc
7+
})
8+
return ids.map(id => idMap[id])
9+
}
10+
311
export const createCachingMethods = ({ collection, cache }) => {
12+
const isMongoose = typeof collection === 'function'
13+
414
const loader = new DataLoader(ids =>
5-
collection
6-
.find({ _id: { $in: ids } })
7-
.toArray()
8-
.then(docs => {
9-
const idMap = {}
10-
docs.forEach(doc => {
11-
idMap[doc._id] = doc
12-
})
13-
return ids.map(id => idMap[id])
14-
})
15+
isMongoose
16+
? collection
17+
.find({ _id: { $in: ids } })
18+
.lean()
19+
.then(docs => remapDocs(docs, ids))
20+
: collection
21+
.find({ _id: { $in: ids } })
22+
.toArray()
23+
.then(docs => remapDocs(docs, ids))
1524
)
1625

1726
const cachePrefix = `mongo-${collection.collectionName}-`

0 commit comments

Comments
 (0)