Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 70 ยท Drivers and applications

MongoDB from Django, and a Node Signup and Login Flow

Connect Django to MongoDB with the MongoDB backend or PyMongo, then build an Express signup and login flow with a unique email index, hashed passwords, sessions and safe error handling.

The two most common web projects people build to learn a database are a blog and a signup and login system. This lesson covers the second one, and the framework question that usually comes first: "Can I use MongoDB with Django?" You will see two ways to connect Django to MongoDB, then walk through a complete Express (Node.js) signup and login flow that stores users in MongoDB with hashed passwords, a unique email index and safe error handling.

Django, Express and a database server cannot run inside this page, so the framework code appears as read-only blocks. Runnable TryIts model the logic that matters: how a unique index rejects a duplicate, how salted hashes make equal passwords look different, and how a login rate limit and a session store behave. The password hash in the TryIts is a toy so that it can run in the browser. It is not secure. Real code uses bcrypt, argon2 or scrypt, as the read-only examples do.

Django and MongoDB: two honest options

Django's built-in ORM was designed for relational databases, and MongoDB is not one. There are two common ways to combine them.

Option 1: the official Django MongoDB Backend

MongoDB publishes a Django database backend, the django-mongodb-backend package, that lets many ORM features work against MongoDB. You install it, point DATABASES at your server, and use models and the ORM much as usual, with extras for MongoDB features such as embedded documents. Check the package documentation for the Django version it supports, because backends are tied to Django releases.

Python
# settings.py (a sketch; check the backend's documentation for exact names and versions)
DATABASES = {
    "default": {
        "ENGINE": "django_mongodb_backend",
        "HOST": "mongodb://localhost:27017",
        "NAME": "mysite",
    }
}
DEFAULT_AUTO_FIELD = "django_mongodb_backend.fields.ObjectIdAutoField"

Things to know: some relational features (certain joins, some migrations behaviors) map differently or are unsupported, so read the compatibility notes before building on a feature. Older community packages such as Djongo translate SQL to MongoDB queries; they are less actively maintained, so prefer the official backend for new work.

Option 2: keep Django's relational database and use PyMongo for MongoDB data

Many projects keep Django's users, admin and sessions in PostgreSQL or SQLite, and use MongoDB only for the data that suits it (events, product catalogs, logs). You call MongoDB through PyMongo (see the Python driver lesson) from your views or a service module:

Python
# mysite/mongo.py
from pymongo import MongoClient
from django.conf import settings

_client = MongoClient(settings.MONGO_URI, serverSelectionTimeoutMS=3000)   # one client per process
db = _client[settings.MONGO_DB]
Python
# articles/views.py
from django.http import JsonResponse
from django.views.decorators.http import require_GET
from mysite.mongo import db

@require_GET
def article_list(request):
    cursor = (
        db.articles.find({"published": True}, {"title": 1, "slug": 1, "_id": 0})
        .sort("created_at", -1)
        .limit(20)
    )
    return JsonResponse({"articles": list(cursor)})

This is simple and explicit, and it leaves Django's authentication untouched. Create the MongoClient once (a module-level object, not one per request), set timeouts, and put indexes in a setup step or management command rather than in views. If you use PyMongo with Django's own User model, store the Django user id (an integer) in your MongoDB documents instead of duplicating passwords.

Designing the users collection

For the Node flow, the users collection stores only what login needs:

JavaScript
{
  _id: ObjectId("..."),
  email: "[email protected]",          // normalized: trimmed and lowercased
  name: "Ada",
  passwordHash: "$2b$12$...",        // output of bcrypt; includes its salt and cost
  createdAt: ISODate("2025-01-15T10:00:00Z"),
  failedLogins: 0
}

Three rules, all for safety:

  1. Never store the password. Store only a salted, slow hash. If your database leaks, hashes buy users time; plain text is a disaster.
  2. Normalize the email (trim, lowercase) before saving and before searching, so [email protected] and [email protected] are the same account.
  3. Enforce uniqueness in the database, not just in application code, with a unique index:
JavaScript
await db.collection("users").createIndex({ email: 1 }, { unique: true })

Two simultaneous signups with the same email can both pass an "is this email taken?" check in code and then both insert. The unique index is what actually guarantees one winner: the loser gets a duplicate key error (error code 11000) that you turn into a friendly message. See Index Types for unique indexes.

The Express signup and login routes

Here is the complete flow with Express, the official mongodb driver and bcrypt. Treat it as a pattern, and adapt packages and versions to your project.

JavaScript
// app.js
import express from "express";
import session from "express-session";
import MongoStore from "connect-mongo";
import bcrypt from "bcrypt";
import { MongoClient } from "mongodb";

const client = new MongoClient(process.env.MONGO_URI);
await client.connect();
const users = client.db("app").collection("users");
await users.createIndex({ email: 1 }, { unique: true });

const app = express();
app.use(express.json());
app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: false,
  store: MongoStore.create({ client, dbName: "app", collectionName: "sessions", ttl: 60 * 60 * 24 }),
  cookie: { httpOnly: true, sameSite: "lax", secure: process.env.NODE_ENV === "production", maxAge: 1000 * 60 * 60 * 24 },
}));

const normalizeEmail = (value) => String(value ?? "").trim().toLowerCase();

app.post("/signup", async (req, res) => {
  const email = normalizeEmail(req.body.email);
  const password = String(req.body.password ?? "");
  if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) return res.status(400).json({ error: "Enter a valid email." });
  if (password.length < 10) return res.status(400).json({ error: "Use at least 10 characters." });

  const passwordHash = await bcrypt.hash(password, 12);
  try {
    const { insertedId } = await users.insertOne({ email, passwordHash, createdAt: new Date(), failedLogins: 0 });
    req.session.userId = insertedId.toString();
    res.status(201).json({ id: insertedId });
  } catch (err) {
    if (err.code === 11000) return res.status(409).json({ error: "That email is already registered." });
    throw err;
  }
});

app.post("/login", async (req, res) => {
  const email = normalizeEmail(req.body.email);
  const user = await users.findOne({ email });
  // One generic message for "no such user" and "wrong password".
  const ok = user && (await bcrypt.compare(String(req.body.password ?? ""), user.passwordHash));
  if (!ok) return res.status(401).json({ error: "Wrong email or password." });

  req.session.regenerate((err) => {          // new session id after login (prevents fixation)
    if (err) throw err;
    req.session.userId = user._id.toString();
    res.json({ ok: true });
  });
});

app.post("/logout", (req, res) => req.session.destroy(() => res.json({ ok: true })));

app.listen(3000);

Why each choice matters:

  • bcrypt.hash(password, 12) adds a random salt and is deliberately slow, so guessing passwords at scale is expensive. The salt and cost are stored inside the hash string, so you need no separate salt field.
  • A generic login error ("Wrong email or password") stops attackers from using the form to find out which emails are registered. Do the hash comparison even when the user does not exist (hash against a dummy value) if you want to hide timing differences too.
  • insertOne plus a unique index turns a race into a clean 409.
  • Sessions in MongoDB (via connect-mongo) use a TTL index to expire old sessions. The cookie holds only a random id: httpOnly (not readable by JavaScript), secure over HTTPS and sameSite.
  • Never build queries from raw request bodies: findOne({ email: req.body.email }) with an object such as { "$ne": null } is a classic NoSQL injection. normalizeEmail forces a string, which blocks it.

For an API without browser sessions, return a signed token (a JWT) instead, and keep the same hashing and uniqueness rules. See the Node.js driver lesson for connection management and Mongoose and other ODMs if you prefer models.

Try it: a unique index and a toy salted hash

The first model reproduces the signup logic. The users stand-in enforces a unique email index and reports the same error code as MongoDB. The toy hash shows the idea of salting: the same password yields different stored values, and verifying means re-hashing with the stored salt. It is deliberately not a real password hash.

JS Signup, duplicate keys and salted hashes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Ada and Bob use the same password, yet their stored values differ because each has its own salt. A leaked table therefore cannot be cracked with one pre-computed list. The "wrong password" and "unknown email" replies are identical on purpose.

Try it: login throttling and a session store

Strong hashes make each guess slow, but you should also limit how many guesses a client can make and expire sessions. The second model adds a failed-login counter with a temporary lockout, and a session store with a TTL, using a fake clock.

JS Lockout after failures, sessions with a TTL

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A lockout needs care. An attacker can lock a victim out by deliberately failing, so many systems lock per IP address plus account, add growing delays, or require a CAPTCHA instead of a hard lock. Rate limiting at the proxy (see security hardening) is also worth having.

A checklist for any signup and login flow

  • Hash with bcrypt, argon2 or scrypt; never MD5 or plain SHA-256 alone.
  • Normalize emails and enforce uniqueness with an index; map error 11000 to a clear response.
  • Return one generic message for login failures; rate limit attempts.
  • Validate input types before querying (strings only), to block operator injection.
  • Use HTTPS, httpOnly and secure cookies, regenerate the session on login and expire sessions with a TTL.
  • Keep the database private and give the app a least-privilege user (see Authentication and Authorization).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why enforce unique emails with a unique index and not only with an application check?

    A check-then-insert has a race window. The unique index is atomic, and the loser receives duplicate key error 11000.
  2. 2. What is the purpose of a salt?

    Each password gets a unique random salt, so identical passwords hash differently and one precomputed list cannot crack them all.
  3. 3. Why return the same error for an unknown email and a wrong password?

    Different messages reveal which accounts exist (user enumeration). Use one generic message.
  4. 4. Which is a valid way to use Django with MongoDB data?

    Both options are common: an ORM backend, or PyMongo alongside Django's relational database.
  5. 5. What does regenerating the session id at login prevent?

    A new id after authentication makes any id the attacker knew useless.

Summary

  • Django can use MongoDB through the official django-mongodb-backend, or you can keep Django's relational database and call PyMongo for MongoDB data.
  • A signup flow normalizes the email, hashes the password with bcrypt, argon2 or scrypt, and inserts into a collection with a unique email index; error 11000 becomes a 409.
  • Login compares the hash, returns one generic error, regenerates the session id and stores sessions with a TTL.
  • Validate and cast input to strings, rate limit attempts, and use secure cookies to close the common holes.
  • The password hash in this lesson's TryIts is a toy for demonstration; use a real password hashing library in production.

Next, see the same driver ideas applied to real projects, starting with Project: Todo API.