Course contentsShow
← Node.js
Lesson 852 of 1,9808. Data Persistence and ORM IntegrationFree lesson

Security Models in NoSQL

You will configure granular access control for collections and individual documents.

In this lesson, you will learn how to transition from broad database-level permissions to granular access control for specific collections and individual documents in your Node.js applications.

When working with NoSQL databases like MongoDB, a common mistake is granting an application user full read/write access to the entire database. In a production environment, we implement Role-Based Access Control (RBAC) to enforce the principle of least privilege.

Granular Collection Access

Instead of giving your backend user dbAdmin rights, you define custom roles. You can restrict a service so it can only perform find operations on a products collection while being blocked from the users collection.

In your Node.js configuration, you ensure your database connection string uses a user scoped to specific resources:

// Example: Connecting with restricted scope
const uri = "mongodb://readonly_user:password@localhost:27017/my_app?authSource=my_app";
const client = new MongoClient(uri);

Document-Level Security

Sometimes, even a collection is too broad. If you have a documents collection where users should only edit their own files, you need Attribute-Based Access Control (ABAC). Since NoSQL databases often evaluate these rules at the application layer, you must integrate security logic directly into your data access layer.

Instead of writing a raw query, wrap your logic in a check that forces a userId filter:

async function getSecureDocument(db, docId, authenticatedUser) {
  // We force a filter on 'ownerId' so users can't access others' data
  return await db.collection('private_files').findOne({
    _id: docId,
    ownerId: authenticatedUser.id 
  });
}

By embedding the ownerId into the query filter, you prevent unauthorized horizontal data access. Even if a user knows the docId, the query will return null if the ownership attribute doesn't match their session. This pattern ensures that your security model is not just a "gate" at the front door, but a persistent constraint on every database interaction within your Node.js code.

Key Takeaway: Secure your NoSQL data by using the principle of least privilege through collection-scoped database users and by programmatically enforcing ownership filters on all document-level queries.