当前位置: 首页 > 软件库 > Web应用开发 > >

mongoose-express-ts

授权协议 MIT License
开发语言 JavaScript
所属分类 Web应用开发
软件类型 开源软件
地区 不详
投 递 者 上官琦
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

Mongoose Node.js Express TypeScript application boilerplate with best practices for API development.

image

The main purpose of this repository is to show a good end-to-end project setup and workflow for writing a Mongoose Node.js Express code in TypeScript complete with middleware, models, routes, and types.

This example comes with a complete REST API to handle Authentication and CRUD features on Users and their corresponding Profile. You may view the API documentation on the Wiki.

Why TypeScript?

While it's true that developing applications on an Untyped language such as JavaScript, is easier to learn and is faster to develop, it will undeniably get harder and harder to grasp as the application grows in scale. This in turn, leads to more run-time errors consuming more development hours, as the team gets accustomed to the growing codebase. And this is what this boilerplate hopes to achieve. By using the TypeScript standard, you'll have better team and code stability with Interface Oriented Development, leading to better standardized codes. TypeScript allows developers to focus more on exposed Interfaces or API, rather than having to know all the code by heart. This makes the codebase easier to maintain with big teams, especially if those teams are composed of developers of different skill levels.

Prerequisites

To build and run this app locally you will need a few things:

Getting started

  • Clone the repository
git clone --depth=1 https://github.com/polcham/mongoose-express-ts.git <project_name>
  • Install dependencies
cd <project_name>
npm install
npm run tsc
  • Build and run the project with auto reload (nodemon)
npm run server
  • Build and run the project
npm run start

Finally, navigate to http://localhost:5000/ and you should see the API running!

Project Structure

The most obvious difference in a TypeScript + Node project is the folder structure. In a TypeScript project, it's best to have separate source and distributable files. TypeScript (.ts) files live in your src folder and after compilation are output as JavaScript (.js) in the dist folder.

The full folder structure of this app is explained below:

Note! Make sure you have already built the app using npm run start

Name Description
config Contains config environment to be used by the config package, such as MongoDB URI, jwtSecret, and etc.
dist Contains the distributable (or output) from your TypeScript build
node_modules Contains all your npm dependencies
REST Contains all API requests to test the routes, used with REST Client VSCode extension
src Contains your source code that will be compiled to the dist dir
src/middleware Contains the middlewares to intercept requests
src/models Models define Mongoose schemas that will be used in storing and retrieving data from MongoDB
src/routes Routes define the endpoints of your API
src/types Contains all your custom types to better handle type checking with TypeScript
src/server.ts Entry point to your express app
package.json File that contains npm dependencies as well as build scripts
tsconfig.json Config settings for compiling server code written in TypeScript
tslint.json Config settings for TSLint code style checking

Configuring TypeScript compilation

TypeScript uses the file tsconfig.json to adjust project compile options.Let's dissect this project's tsconfig.json, starting with the compilerOptions which details how your project is compiled.

"compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es6",
    "noImplicitAny": true,
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "dist",
    "baseUrl": ".",
    "paths": {
      "*": ["node_modules/*", "src/types/*"]
    }
  }
compilerOptions Description
"module": "commonjs" The output module type (in your .js files). Node uses commonjs, so that is what we use
"esModuleInterop": true, Allows usage of an alternate module import syntax: import foo from 'foo';
"target": "es6" The output language level. Node supports ES6, so we can target that here
"noImplicitAny": true Enables a stricter setting which throws errors when something has a default any value
"moduleResolution": "node" TypeScript attempts to mimic Node's module resolution strategy. Read more here
"sourceMap": true We want source maps to be output along side our JavaScript. See the debugging section
"outDir": "dist" Location to output .js files after compilation
"baseUrl": "." Part of configuring module resolution. See path mapping section
paths: {...} Part of configuring module resolution. See path mapping section

The rest of the file define the TypeScript project context.The project context is basically a set of options that determine which files are compiled when the compiler is invoked with a specific tsconfig.json.In this case, we use the following to define our project context:

"include": [
        "src/**/*"
    ]

include takes an array of glob patterns of files to include in the compilation. This project is fairly simple and all of our .ts files are under the src folder.

Running the build

All the different build steps are orchestrated via npm scripts.Npm scripts basically allow us to call (and chain) terminal commands via npm.This is nice because most JavaScript tools have easy to use command line utilities allowing us to not need grunt or gulp to manage our builds.If you open package.json, you will see a scripts section with all the different scripts you can call.To call a script, simply run npm run <script-name> from the command line.You'll notice that npm scripts can call each other which makes it easy to compose complex builds out of simple individual build scripts.Below is a list of all the scripts this template has available:

Npm Script Description
tsc Transpiles TypeScript codes to JavaScript.
watch-tsc Transpiles TypeScript codes to JavaScript, with auto reload.
deploy Runs node on dist/server.js which is the app's entry point.
watch-deploy Runs node on dist/server.js which is the app's entry point, with auto reload.
server Transpiles TypeScript codes to JavaScript then run node on dist/server.js with auto reload.
start Transpiles TypeScript codes to JavaScript then run node on dist/server.js.

Since we're developing with TypeScript, it is important for the codes to be transpiled first to JavaScript before running the node server. It is best to deploy the app using: npm run server or npm run start command.

VSCode Extensions

To enhance your development experience while working in VSCode, I provided you with a list of suggested extensions while working on this project:

Dependencies

Dependencies are managed through package.json.In that file you'll find two sections:

dependencies

Package Description
bcryptjs Library for hashing and salting user passwords.
config Universal configurations for your app.
express Node.js web framework.
express-validator Easy form validation for Express.
gravatar Generate Gravatar URLs based on gravatar specs.
http-status-codes HTTP status codes constants.
jsonwebtoken JsonWebToken implementation for Node.js.
mongoose MongoDB modeling tool in an async environment.
request Simplified HTTP client for Node.js.
typescript Typed superset of JavaScript.

devDependencies

Since TypeScript is used, dependencies should be accompanied with their corresponding DefinitelyTyped @types package.

Package Description
@types/bcryptjs DefinitelyTyped for bcryptjs
@types/config DefinitelyTyped for config
@types/express DefinitelyTyped for express
@types/gravatar DefinitelyTyped for gravatar
@types/jsonwebtoken DefinitelyTyped for jsonwebtoken
@types/mongoose DefinitelyTyped for mongoose
concurrently Run multiple commands concurrently
nodemon Reload node application on code changes

To install or update these dependencies you can use npm install or npm update.

  • typescript+express是在我感觉js维护难后发现可以使用ts来作为开发 那我就选择去学习ts,但是当我学完ts后发现ts+express的项目怎么创建是我最懵逼的 而网上的资源也不多, 可能用的人也不多吧 我就想要先发一篇这样的博客,让自己能够时刻记住也能让更多人看到吧. 首先准备下开发环境 查看nodejs版本号 ,我使用的是 v16.13.1 node -v 查看npm版本 n

  • 使用TypeScript+Express+NodeJS+MongoDB 开发 Web APIs,如有错误可以击提issue ,如果觉得ok,请点个star , 送人玫瑰、手有余香 仓库地址 ➡️FE_note 本系列文章 搭建环境 构建路由 连接数据库 nodeJs 错误处理 权限认证与数据加密 下一步计划 nodeJs 双向身份验证(Two-Factor) 搭建开发环境 npm init -

  • 前言 记录下ts实现后端接口的操作。 安装 先进目录初始化,然后安装依赖 cnpm i express mongoose body-parser bcryptjs jsonwebtoken morgan cors validator helmet dotenv multer http-status-codes -S cnpm i typescript @types/node @types/exp

  • 安装依赖 npm i express mongoose ts-node typescript nodemon @types/express @types/node express-session @types/express-session 新建 tsconfig.json { "compilerOptions": { "target": "es5", "

  • 使用TypeScript+Express+NodeJS+MongoDB 开发 Web APIs,如有错误可以击提issue ,如果觉得ok,请点个star , 送人玫瑰、手有余香 仓库地址 ➡️FE_note 本系列文章 搭建环境 构建路由 连接数据库 nodeJs 错误处理 权限认证与数据加密 nodeJs错误处理 通过上面的学习,存在一个很大问题,就是我们把操作数据库的错误抛给了clien

  • 使用TypeScript+Express+NodeJS+MongoDB 开发 Web APIs,如有错误可以击提issue ,如果觉得ok,请点个star , 送人玫瑰、手有余香 仓库地址 ➡️FE_note 本系列文章 搭建环境 构建路由 连接数据库 nodeJs 错误处理 权限认证与数据加密 引入MongoDB MongoDB安装与入门 目录结构 ├── README.md ├── pac

  •         MongoDB现在绝对是市面上最受欢迎的noSql数据库,本文将简单讲解Mongoose和MongoDB的语法和特点。 目录 什么是MongoDB和Mongoose? 在Node中链接MongoDB数据库 定义Mongoose的对象模式schema MongoDB的增删改查         查找和创建操作              更新操作         删除操作​​​​​​​

  • mongoose、multer、验证、缓存、安全等 官方nestjsAPI地址 1.nestjs结合mongoose 1.1 安装mongoose和nest相关 cnpm i @nestjs/mongoose mongoose --save 1.2 配置连接数据库 方式1,直接配置 // mongo.module.ts import { Module } from '@nestjs/commo

 相关资料
  • Node Express Mongoose A boilerplate application for building web apps using express, mongoose and passport. Read the wiki to understand how the application is structured. Usage git clone https://githu

  • Vue-Admin-Express-Mongoose 基于Vue2.0(Vue-cli)+ElementUI+Express+Mongoose的全栈开发环境 前端页面部分基于vueAdmin项目,修复了其中的一些BUG。 OnlineDemo 效果 用法 安装依赖 npm install 开发环境 首先,启动Express服务(4501端口),提供API接口,请确保已经安装MongoDB npm

  • Nodejs Express Mongoose Demo This is a demo application illustrating various features used in everyday web development, with a fine touch of best practices. The demo app is a blog application where us

  • Express & mongoose REST API Boilerplate in ES6 with Code Coverage Sponsor You can support the project by checking out our sponsor page. It takes only one click: Overview This is a boilerplate applicat

  • Node boilerplate This is my node boilerplate starter kit. I will continue to update with the latest tech to help make make node servicessuper easy and efficient to kick start. Whats out the box? Frame

  • 问题内容: 创建新用户帐户后,我创建了newUser,这是一个Mongoose模型实例,如下所示: 该对象的实际数据位于 _doc 属性中,尽管存在getter和setter,所以您可以运行: 这样就可以了。我跑: 将用户保存到会话。到目前为止,一切都很好。 但是,在后续请求中,request.session.user似乎只是_doc中的内容。例如: 很好,但这意味着我无法运行例如 request