Skip to content

Instantly share code, notes, and snippets.

@msroot
Last active March 3, 2021 14:43
Show Gist options
  • Save msroot/52ba361b8e1e520a07e490df94d802e2 to your computer and use it in GitHub Desktop.
Save msroot/52ba361b8e1e520a07e490df94d802e2 to your computer and use it in GitHub Desktop.
mongoose hasMany plugin
//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