Skip to content

Commit 9b593c7

Browse files
committed
Adds conditional check on mongoose
- Using .lean() and not .toArray() on queries when mongoose
1 parent 8dab732 commit 9b593c7

File tree

1 file changed

+19
-10
lines changed

1 file changed

+19
-10
lines changed

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)