How to prefix filter/scopes to all queries of mongoose implicitly?

190 views
Skip to first unread message

Jackal

unread,
Nov 28, 2019, 3:15:59 AM11/28/19
to Mongoose Node.JS ODM
Looking at using mongoose to build a multi tenant application with logical separation using a tenant_id field in every document/table.
I am looking for a way to prefix a filter for tenant_id so that I always work with the filtered set (subset belonging to that particular tenant) of documents.  Something along the lines of "pre" hook in which I can list the action and perform some additional steps.  Any / Every interaction with the mongo db should be filtered automatically by this filter/scope.

Idea is that I dont want to add explicit filter for tenant_id into each & every mongoose calls in the code and what this filter to be implicit.

Can someone help/guide me towards how to achieve this? 

Thanks

Rob Ludwig

unread,
Dec 2, 2019, 3:58:02 PM12/2/19
to Mongoose Node.JS ODM
You might be looking for discriminators. You would make the overall model and then create a discriminated sub-model for each tenant. You could also do this with MongoDB views, in much the same way. However mongoose doesn't have great support for views, so you'd be on your own.
Reply all
Reply to author
Forward
0 new messages