Skip to content

AndrewJBateman/node-mongodb-zod

Repository files navigation

⚡ Node MongoDB Zod

  • Node.js + Express used with the zod library to interract with a MongoDB database
  • Note: to open web links in a new window use: ctrl+click on link

GitHub repo size GitHub pull requests GitHub Repo stars GitHub last commit

📄 Table of contents

📚 General info

  • Controllers: One for each resource: product, session and user
  • Middleware: there are three - to deserialize user, require user & validate resource
  • Models: one for each resource: product, session and user
  • Schema: used by validate resource middleware
  • Utils: utilities for connection to the database, jwt & logger
  • Data flow: HTTP endpoint <-> ( Middleware ) <-> Controller <-> Service <-> Database
  • mongoose v6 legacy type HookNextFunction has been removed
  • mongoose queries with the lean option used to get results faster
  • lodash omit used to return a copy of the object minus the filtered item - user password in this case
  • zod library used for data validation with automatic typing, as the code uses typescript data types

📷 Screenshots

Image

📶 Technologies

  • Node.js v14 Javascript runtime using the Chrome V8 engine
  • Express v4 web framework for node
  • MongoDB Atlas cloud database service
  • mongoose v6 mongodb object modelling for node.js
  • pino v7 very low overhead Node.js logger.
  • dayjs v1 minimalist JavaScript library that parses, validates, manipulates & displays dates and times
  • zod v3 TypeScript-first schema declaration and validation library. A schema can be any data type
  • JWT tokens using RS256 algorithm
  • nanoid A tiny (130bytes), fast (2x faster than UUID), secure, URL-friendly, unique string ID generator for JavaScript. ID size is only 21 symbols

💾 Setup

  • npm i to install dependencies
  • Create .env and add database credentials - see .example.env
  • Create public & private keys using JWT with the RS256 algorithm option selected. Take care with the format and the -----END PRIVATE KEY---- etc. to avoid an "ERR_OSSL_PEM_BAD_END_LINE" error
  • MongoDB has to be running - I used the cloud database MongoDB Atlas instead of installing MongoDB on my hard drive
  • yarn dev or npm run dev runs app in the development mode with auto-restart.
  • Open http://localhost:5000 to view it in the browser.

🔧 Testing

  • Postman and Thunder Client used to simulate HTTP endpoints
  • See test.txt for tests that have passed

💻 Code Examples

  • Function to create new user to schema format; email, password, password confirmation & name strings
export const createUserHandler = async (
  req: Request<{}, {}, CreateUserInput["body"]>,
  res: Response
) => {
  try {
    const user = await createUser(req.body);
    return res.send(user);
  } catch (err: any) {
    logger.error(err);
    return res.status(409).send(err.message);
  }
};

🆒 Features

  • Nano ID id generator uses 21 symbols and is only 130bytes.

📋 Status, Testing & To-Do List

  • Status: Code complete and part tested
  • To-Do: Complete testing using Thunder Client

👏 Inspiration

📁 License

  • N/A

✉️ Contact