Best practices when writing to a Collection from a different file than where it is defined

Are there any best practices when writing to the db from a different file than where a Collection is defined?

For example, I’m working with a 3rd-party API and would like to write some of data to the db. I’m calling a method from the client, waiting for the result from the API on the server and then inserting.

Another example would be if you have CollectionA and after successful insert, you want to write to CollectionB.

Would it be better to:
1) Import Collection and call insert directly

import { Collection } from '/imports/api/collection.js'

// do stuff

Collection.insert({...})

Pro: Less code
Con: You might have writes like insert / update / upsert sprinkled in different files. Something about this feels not great but maybe it’s fine.

– OR –

2) Define a function that wraps Collection.insert and import the function into the file

import { insertDocument } from '/imports/api/collection.js'

// do stuff

insertDocument({...})

Pro: All your writes would be in one file. Seems better for validation and maintaining.
Con: More code

Or maybe there’s another way that I’m not even thinking of. Curious to hear your thoughts.

#2 is definitely way easier for maintenance.

Yet, there is always search to help find all the imports. But if you are using a generic collection name that can be the same as the variable names that you use, this can add to the difficulty of finding all the queries

1 Like

Hi @jam ,

I (almost) always organize the backend code in separate files. So there will be files for inserts, update and remove (if there are “enough” functions/code for this collection - otherwise I keep it all in one file where the collection is defined).

The file where the collection is defined is then mainly used for find, findOne and aggregations.

As @rjdavid wrote, this helps a lot with keeping things clean and is indeed much easier to maintain (the separate files include error handling, specific error codes and other logic).

I still have files with > 1000 lines of code that would be better split further but this work always comes last (basically is never done).

1 Like