How to add a document to a specific database AND collection in the URI

You can definitely write to multiple databases and collection with both the MongoDB Node.js driver and Mongoose. See the doc for both but it’s 100% sure you can with both.

Mongoose is an extra layer on top of the MongoDB Node.js driver though. I’m not a fan as I prefer to use directly the driver and all the features, but it’s your choice. Mongoose helps to enforce a schema as you have to work with models, but MongoDB is schemaless by design so nothing forces you to enforce a model / schema by default.

That being said, if you need or want to enforce some constraints, there are a couple of ways to do so:

  • In the back-end
  • In MongoDB

If you do so in the back-end (like by using Mongoose or some other JSON schema modules), you can’t guarantee that another client (=back-end) or direct command lines sent to the cluster will respect these constraints.

The only wait to enforce a constraint for sure, is to enforce it with the $jsonSchema directly in the MongoDB collection in the validator.

Read this for more details:

Cheers,
Maxime.

2 Likes