1. TypeScript Express tutorial #1. Middleware, routing, and controllers 2. TypeScript Express tutorial #2. MongoDB, models and environment variables

In this part of the Express TypeScript tutorial, we cover using a MongoDB database. To do that properly, we also learn the concept of environment variables . Since we follow the MVC pattern, we introduce the idea of a model . Just as in the previous part of the tutorial , all of the code from this part is in the express-typescript repository. Feel free to give it a star if you have not yet done so.

TypeScript Express tutorial #2: Express MongoDB

To use Express MongoDB in this article, we use a platform called mLab . It provides hosting for your database and has a free plan also, called the sandbox . After creating a new database, you can see its URI. In my case it is mongodb : //<dbuser>:<dbpassword>@ds227594.mlab.com:27594/tutorial .

The URI includes the dbuser and dbpassword . These are not the credentials to your mLab account, but to the database itself. To create a user for your database, go to the tab named users .

In this Express MongoDB part of the tutorial, we use Mongoose . It is an Object Data Modeling (ODM) library that makes interacting with your MongoDB easier.

The question is how to provide credentials to our application. Even though for some the first thought might be to hardcode it into our code, it is not that good of an idea for various reasons. First of them is that you probably wouldn’t want to submit the credentials to your repository. The second reason is that you might wish to have different databases for each of your environment, for example on production and staging. The solution here is using environment variables .

Environment variables

The environment variables are values accessible in the environment in which the program runs. The operating system sets some of them up when it boots. The variables can be either global or just inside of one process. In Node.js, you have access to them through the process . env global object.

const MONGO_USER = process.env.MONGO_USER;

The easiest way to set them is to do it in your NPM scripts:

"scripts": { "dev": "MONGO_USER=mwanago MONGO_PASSWORD=myPassword MONGO_PATH=@ds227594.mlab.com:27594/tutorial ts-node ./src/server.ts" }

That does not seem like a good solution either. Another approach that you can take is to create a file named . env in which you store all your environment variables. The most popular way to handle a file like that is to use the dotenv package. First, create the . env file in the parent directory of your project.

.env MONGO_USER=mwanago MONGO_PASSWORD=myPassword MONGO_PATH=@ds227594.mlab.com:27594/tutorial PORT=5000 As you can see, I’ve also created the PORT variable. It might be useful if you would want to change the port on which your application runs

At the beginning of your server . ts file (the one that is the entrypoint of your project) import dotenv / config . Thisimport runs the config function for you and loads the . env file. The only thing left to establish the connection to our database is to run the mongoose . connection function.

src/server.ts import * as mongoose from 'mongoose'; import 'dotenv/config'; const { MONGO_USER, MONGO_PASSWORD, MONGO_PATH, } = process.env; mongoose.connect(`mongodb://${MONGO_USER}:${MONGO_PASSWORD}${MONGO_PATH}`); It is a convention for environmental variables to be in uppercase.

Since you definitely shouldn’t commit your . env file, I recommend adding it to your . gitignore .

Validating environment variables

Forgetting to set one of your environment variables might cause your application to malfunction. To prevent it, we can verify them. To do that, I use the envalid package.

src/utils/validateEnv.ts import { cleanEnv, str, } from 'envalid'; function validateEnv() { cleanEnv(process.env, { MONGO_PASSWORD: str(), MONGO_PATH: str(), MONGO_USER: str(), PORT: port(), }); }

It throws an error if you if you forgot to provide one of the defined variables or if they are of a wrong type.

You can put the initialization of the database connection in the App class, and the validation of environment variables in the server.ts file.

src/server.ts import 'dotenv/config'; import App from './app'; import PostsController from './posts/posts.controller'; import validateEnv from './utils/validateEnv'; validateEnv(); const app = new App( [ new PostsController(), ], ); app.listen(); src/server.ts import * as bodyParser from 'body-parser'; import * as express from 'express'; import * as mongoose from 'mongoose'; import Controller from './interfaces/controller.interface'; class App { public app: express.Application; constructor(controllers: Controller[]) { this.app = express(); this.connectToTheDatabase(); this.initializeMiddlewares(); this.initializeControllers(controllers); } public listen() { this.app.listen(process.env.PORT, () => { console.log(`App listening on the port ${process.env.PORT}`); }); } private initializeMiddlewares() { this.app.use(bodyParser.json()); } private initializeControllers(controllers: Controller[]) { controllers.forEach((controller) => { this.app.use('/', controller.router); }); } private connectToTheDatabase() { const { MONGO_USER, MONGO_PASSWORD, MONGO_PATH, } = process.env; mongoose.connect(`mongodb://${MONGO_USER}:${MONGO_PASSWORD}${MONGO_PATH}`); } } export default App; Express MongoDB with Mongoose

Once we have the connection established, let’s dig into the Express MongoDB and Mongoose more. MongoDB is a non-relational database that stores the data in JSON-like documents. Fields can vary from adocument to document, and the data structure can change over time.

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

代码区博客精选文章
分页:12
转载请注明
本文标题:TypeScript Express tutorial #2. MongoDB, models and environment variables
本站链接:https://www.codesec.net/view/621246.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(15)