-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
61 lines (58 loc) · 1.46 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import mongoose from 'mongoose'
export const populatingLookupPreserveNullQuery = (
collectionName: string,
fieldName: string,
foreignFieldName = '_id'
): mongoose.PipelineStage[] => {
return [
{
$lookup: {
from: collectionName,
let: { [fieldName]: `$${fieldName}` },
pipeline: [
{
$match: {
$expr: {
$eq: [`$${foreignFieldName}`, `$$${fieldName}`]
}
}
}
],
as: fieldName
}
},
{ $unwind: { path: `$${fieldName}`, preserveNullAndEmptyArrays: true } }
]
}
export const populatingLookupQuery = (
collectionName: string,
fieldName: string,
foreignFieldName = '_id'
): mongoose.PipelineStage[] => {
return [
{
$lookup: {
from: collectionName,
localField: fieldName,
foreignField: foreignFieldName,
as: fieldName
}
},
{ $unwind: { path: `$${fieldName}` } }
]
}
// https://github.com/Automattic/mongoose/issues/4727#issuecomment-349381917
export const hydratePopulated = (
model: mongoose.Model<any>,
json: Record<string, any>,
populated: string[]
): mongoose.Document => {
const document = model.hydrate(json)
for (const path of populated) {
if (!json[path]) { continue }
const options = model.schema.paths[path]?.options
if (!options?.ref) { continue }
document[path] = mongoose.model(options.ref).hydrate(json[path])
}
return document
}