Last active
March 3, 2021 14:43
-
-
Save msroot/52ba361b8e1e520a07e490df94d802e2 to your computer and use it in GitHub Desktop.
mongoose hasMany plugin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//dbPlugins.js | |
import mongoose from 'mongoose' | |
export const hasMany = (schema, options) => { | |
for (const [className, finder] of Object.entries(options)) { | |
const plural = schema.base._pluralize(className) | |
schema.methods[plural] = function (cb) { | |
for (const [k, v] of Object.entries(finder)) { | |
finder[k] = v.toString()[0] === '$' ? this.get(v.replace('$', '')) : v | |
} | |
return mongoose.model(className).find(finder, cb) | |
} | |
} | |
} | |
// model.js | |
import { hasMany } from '../utils/dbPlugins' | |
modelSchema.plugin(hasMany, { | |
Coverage: { policy: '$_id' }, | |
Document: { className: 'Policy', classId: '$_id' }, | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment