Automattic / mongoose

MongoDB object modeling designed to work in an asynchronous environment.
https://mongoosejs.com
MIT License
26.8k stars 3.81k forks source link

Question: with Middleware or Plugins, is it possible to execute queries using a separate mongoose connection? #14726

Closed ptrin closed 1 week ago

ptrin commented 2 weeks ago

Prerequisites

Issue

I'd like to be able to load data from a cluster in another region inside of a Middleware or Plugin. For example, if a document is "flagged" with a storageRegion it would indicate it should use a separate connection to query data from (with that document then being merged with the one being returned from the primary connection).

Pseudocode

pre('save')
  - Save configurable "sensitive properties for schema" to collection of same name in alternate region
  - Store reference to ObjectId of saved doc and region on document
  - Save document
post('find, aggregate')
  - If document has region flag, load and merge properties from that region's document

Should this be possible with the current Middleware/Plugin API?

vkarpov15 commented 2 weeks ago

In theory yes. Mongoose can't replace the collection the current operation is using, but you can trigger a new operation from your middleware. For example:

schema.pre('save', async function() {
  const connectionForRegion = connections[this.region];
  await connectionForRegion.model(this.constructor.modelName).updateOne({ _id: this._id }, { $set: { someProperty: this.someProperty } });
});

Does the above help?

Potentially related issue: #13546

ptrin commented 2 weeks ago

Yes, that's a very helpful response, thank you! 😄