Employees List
Name | Position | Level | Action |
---|---|---|---|
{{employee.name}} | {{employee.position}} | {{employee.level}} |
|
` }) export class EmployeesListComponent implements OnInit { employees$: Observable
= new Observable(); constructor(private employeesService: EmployeeService) { } ngOnInit(): void { this.fetchEmployees(); } deleteEmployee(id: string): void { this.employeesService.deleteEmployee(id).subscribe({ next: () => this.fetchEmployees() }); } private fetchEmployees(): void { this.employees$ = this.employeesService.getEmployees(); } }
As you can notice,
EmployeesListComponent
is a TypeScript class that is decorated with the
@Component
decorator. The
@Component
decorator is used to indicate that this class is a component. The
selector
property is used to specify the HTML tag that will be used to display this component. Spoiler alert: We won’t use this selector at all. Instead, we’ll register the component as a route. The
template
property is used to specify the HTML template that will be used to display this component.
The implementation of the class contains the logic for the component. The
ngOnInit()
method is called when the component is rendered on the page. It’s a good place to fetch the list of employees. For that, we’re using the
EmployeeService
we created earlier. The
getEmployees()
method returns an observable. We subscribe to it with the
async
pipe in the template. This will automatically render the list of employees as soon as the data is available. We’re using a table to display the employees together with a few Bootstrap classes that make it look nicer.
There are also a few actions in the template—for editing, deleting, and adding new employees. The
[routerLink]
attribute is used to navigate to the ‘/employees/edit/:id’ route, which we’ll implement later in the tutorial. The
(click)
event is used to call the
deleteEmployee()
method. This method, implemented in the class, uses the
EmployeeService
to delete an employee.
Now that we’ve created our component, we need to register it as a route in the ‘app.routing.module.ts’ file. Replace the contents of the file with the following:
mean-stack-example/client/src/app/app.routing.module.ts
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { EmployeesListComponent } from './employees-list/employees-list.component'; const routes: Routes = [ { path: '', redirectTo: 'employees', pathMatch: 'full' }, { path: 'employees', component: EmployeesListComponent }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
Then, go to the ‘src/app/app.component.ts’ file and remove the extraneous content from the template. Make sure you leave only the tag, wrapped in a tag.
mean-stack-example/client/src/app/app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` ` }) export class AppComponent { }
Let’s refresh the browser and see if everything is working.
We have a table but we don’t see any employees yet. Let’s create a new page for adding employees.
We need a form for filling in name, position, and level, to create a new employee. For editing existing employees, we’ll need a similar form. Let’s create an
EmployeeForm
component and reuse it for both adding and editing.
ng generate component employee-form -m app
Let’s start by importing the
ReactiveFormsModule
in our
AppModule
:
mean-stack-example/client/src/app/app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { EmployeesListComponent } from './employees-list/employees-list.component'; import { EmployeeFormComponent } from './employee-form/employee-form.component'; import { HttpClientModule } from '@angular/common/http'; import { ReactiveFormsModule } from '@angular/forms'; // <-- add this line @NgModule({ declarations: [ AppComponent, EmployeesListComponent, EmployeeFormComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, ReactiveFormsModule // <-- add this line ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Now, we can use Angular’s
FormBuilder
to create a reactive form:
mean-stack-example/client/src/app/employee-form/employee-form.component.ts
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { BehaviorSubject } from 'rxjs'; import { Employee } from '../employee'; @Component({ selector: 'app-employee-form', template: ``, styles: [ `.employee-form { max-width: 560px; margin-left: auto; margin-right: auto; }` ] }) export class EmployeeFormComponent implements OnInit { @Input() initialState: BehaviorSubject
= new BehaviorSubject({}); @Output() formValuesChanged = new EventEmitter
(); @Output() formSubmitted = new EventEmitter
(); employeeForm: FormGroup = new FormGroup({}); constructor(private fb: FormBuilder) { } get name() { return this.employeeForm.get('name')!; } get position() { return this.employeeForm.get('position')!; } get level() { return this.employeeForm.get('level')!; } ngOnInit() { this.initialState.subscribe(employee => { this.employeeForm = this.fb.group({ name: [ employee.name, [Validators.required] ], position: [ employee.position, [ Validators.required, Validators.minLength(5) ] ], level: [ employee.level, [Validators.required] ] }); }); this.employeeForm.valueChanges.subscribe((val) => { this.formValuesChanged.emit(val); }); } submitForm() { this.formSubmitted.emit(this.employeeForm.value); } }
There’s a lot of code here but there isn’t anything groundbreaking to it. We’re just using the
FormBuilder
to create a reactive form with three fields and we’re also adding validation to the form. The template is displaying the error messages in case there’s a validation error. We’re using an
@Input()
to pass in the initial state of the form from the parent component. The type of the
@Input()
is
BehaviorSubject
because we might pass async data into the form.
For example, the parent component might fetch the employee data from an API and pass it into the form. The child component will get notified when new data is available. The
@Output()
is an event emitter that will emit the form values whenever the form is submitted. The parent will handle the submission and send an API call.
The next step is to implement the
AddEmployeeComponent
:
ng generate component add-employee -m app
Replace the content of the newly created file with the following:
mean-stack-example/client/src/app/add-employee/add-employee.component.ts
import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { Employee } from '../employee'; import { EmployeeService } from '../employee.service'; @Component({ selector: 'app-add-employee', template: `References[edit]
- ^ "us-en_cloud_learn_mean-stack-explained". www.ibm.com. IBM Cloud Education. 2019-05-09. Archived from the original on 2020-05-14. Retrieved 2020-02-16.
- ^ Dickey, Jeff (2014-09-24). Write Modern Web Apps with the MEAN Stack: Mongo, Express, AngularJS, and Node.js. Peachpit Press. ISBN 9780133962376.
- ^ "MERN Stack Explained". Archived from the original on 2023-04-27.
- ^ "How to Use MERN Stack: A Complete Guide". Archived from the original on 2023-03-21.
- ^ "LAMP vs MEAN, Deciding the right stack for your startup". www.linkedin.com. Retrieved 2020-02-16.
- ^ "The MEAN Stack: MongoDB, ExpressJS, Angular and Node.js". Tumblr. Apr 30, 2013.
- ^ "Mean Stack". LinkedIn.
- ^ "The most popular database for modern apps". MongoDB. Retrieved 2020-02-16.
- ^ "Express - Node.js web application framework". expressjs.com. Retrieved 2020-02-16.
- ^ II, Thomas Hunter (2019-03-28). "Why should I use a Reverse Proxy if Node.js is Production-Ready?". Medium. Retrieved 2020-02-16.
- ^ "Features - Server Side Rendering | Next.js". nexts.org. Retrieved 2020-02-16.
- ^ "JavaScript Everywhere and the Three Amigos (WebSphere: Into the wild BLUE yonder!)". 2013-11-14. Archived from the original on 2013-11-14. Retrieved 2020-02-16.
Software components[edit]
MongoDB[edit]
MongoDB is a NoSQL database program that uses JSON-like BSON (binary JSON) documents with optional schemas.
The role of the database in the MEAN stack is very commonly filled by MongoDB because its use of JSON-like documents for interacting with data as opposed to the row/column model allows it to integrate well with the other (JavaScript-based) components of the stack.[8]
Express.js[edit]
Express.js (also referred to as Express) is a modular web application framework package for Node.js.[9]
While Express is capable of acting as an internet-facing web server, even supporting SSL/TLS out of the box, it is often used in conjunction with a reverse proxy such as NGINX or Apache for performance reasons.[10]
Angular and alternatives[edit]
Typically data is fetched using Ajax techniques and rendered in the browser on the client-side by a client-side application framework, however as the stack is commonly entirely JavaScript-based, in some implementations of the stack, server-side rendering where the rendering of the initial page can be offloaded to a server is used so that the initial data can be prefetched before it is loaded in the user's browser.[11]
Node.js[edit]
Node.js is the application runtime that the MEAN stack runs on.
The use of Node.js, which is said to represent a "JavaScript Everywhere" paradigm,[12] is integral to the MEAN stack which relies on that concept.
Frequently Asked Questions
Is MEAN stack better than MERN?
Ans: The choice between the MEAN and MERN stack depends on the project’s specific needs and requirements. Both stacks have their advantages and disadvantages. MEAN stack uses Angular, which provides a complete framework and is more established. MERN stack uses React, which is more flexible and has recently gained popularity. Connect with MEAN stack development company to get your work done cost-effectively.
What is the difference between MEAN and MERN technology?
Ans: The front-end framework is the primary difference between MEAN and MERN technology. MEAN stack uses Angular, while the MERN stack uses React. Additionally, the MEAN stack uses MongoDB as its database, while the MERN stack uses MongoDB or any other NoSQL database. Both stacks use Node.js as the back-end framework.
The MEAN stack is a JavaScript-based framework for developing web applications. MEAN is named after MongoDB, Express, Angular, and Node, the four key technologies that make up the layers of the stack.
There are variations to the MEAN stack such as MERN (replacing Angular.js with React.js) and MEVN (using Vue.js). The MEAN stack is one of the most popular technology concepts for building web applications.
The MEAN architecture is designed to make building web applications in JavaScript and handling JSON incredibly easy.
At the very top of the MEAN stack is Angular.js, the self-styled “JavaScript MVW Framework” (MVW stands for “Model View and Whatever”).
Angular.js allows you to extend your HTML tags with metadata in order to create dynamic, interactive web experiences much more powerfully than, say, building them yourself with static HTML and JavaScript (or jQuery).
Angular has all of the bells and whistles you’d expect from a front-end JavaScript framework, including form validation, localization, and communication with your back-end service.
The next level down is Express.js, running on a Node.js server. Express.js calls itself a “fast, unopinionated, minimalist web framework for Node.js,” and that is indeed exactly what it is.
Express.js has powerful models for URL routing (matching an incoming URL with a server function), and handling HTTP requests and responses. By making XML HTTP requests (XHRs), GETs, or POSTs from your Angular.js front end, you can connect to Express.js functions that power your application.
Those functions, in turn, use MongoDB’s Node.js drivers, either via callbacks or using promises, to access and update data in your MongoDB database.
If your application stores any data (user profiles, content, comments, uploads, events, etc.), then you’re going to want a database that’s just as easy to work with as Angular, Express, and Node.
That’s where MongoDB comes in: JSON documents created in your Angular.js front end can be sent to the Express.js server, where they can be processed and (assuming they’re valid) stored directly in MongoDB for later retrieval.
Again, if you want to easily get the best of MongoDB, you’ll want to look at MongoDB Atlas. This will allow you built-in full database security and cross-cloud scalability with the click of a button. More on that later on this page.
MEAN applications can be used in many ways with a cross-platform write-once approach. While MEAN is particularly suited to real-time applications, particularly those running natively in the cloud and single-page (dynamic) web applications built in Angular.js, it can be used for other use cases such as:
There are many more uses for the MEAN stack, as well.
Since all the components are based on JavaScript and JSON, the integration between the components of the stack is intuitive and straightforward.
Additionally, the E and A of MEAN (Express and Angular) are two of the most popular and well-supported JavaScript frameworks for back-end and front-end development, respectively. Express makes routing and managing HTTP requests and responses super easy, and includes great support for middleware to handle JSON endpoints and form posts. Angular is a powerful tool for building dynamic HTML pages that communicate with a back-end server.
Whether you’re building a high-throughput API, a simple web application, or a microservice, MEAN is the ideal stack for building Node.js applications.
All of the MEAN stack components are open source in nature and therefore allow a generous, free-of-charge opportunity for developers.
JavaScript is a great modern language, but it wasn’t initially designed to build back-end servers. Since the foundation of the MEAN stack is JavaScript, including the back-end server, it might come with concurrency and performance problems at scale due to JavaScript nature.
Additionally, since the development opportunity is so rapid, business and server logic might suffer from poor isolation, making potential spaghetti code and bad practices a reality along the way.
Finally, although there are many guides and tutorials out there, they generally will not include concrete JS coding guidelines appropriate for this stack. Therefore, something that worked really well for one application might surface issues for another.
MEAN follows the traditional three-tier stack pattern, including the display tier (Angular.js), application tier (Express.js and Node.js), and database tier (MongoDB).
If you’re building a JavaScript application, particularly in Node.js, then you should give MEAN a serious look.
MongoDB stores data in a JSON-like format (BSON, a binary JSON extension), the MongoDB Query Language (MQL) is defined in JSON, and its command line interface (CLI) is a JavaScript interpreter. Not only is MongoDB essentially a JavaScript/JSON data store, but it’s full of advanced features like indexing and querying deep into JSON documents, has powerful native Node.js drivers, and is designed for horizontal scale-out. It’s even easier to develop apps in the cloud using MongoDB Atlas, the cloud-native database as a service from the creators of MongoDB.
Whether you’re building a high-throughput API, a simple web application, or a microservice, MEAN is the ideal stack for building Node.js applications.
The MongoDB Node.js driver makes working with MongoDB from inside a Node.js script simple and intuitive for developers — saving developers time and increasing their productivity.
Next, you'll need a MongoDB database. The easiest way to get started with MongoDB is to create a free cluster in MongoDB Atlas, MongoDB's fully managed, multi-cloud document database as a service.
Atlas databases are easily deployed and scaled, providing you with a consistent URI to connect. See the official MongoDB documentation on connecting to a cluster.
Along the way, Atlas connections come with built-in username/password and TLS end-to-end encryption by default. Additionally, these connections allow you to utilize advanced MongoDB security features such as certificate/IAM authentication, LDAP, Encryption-at-rest, and Auditing with the click of a button.
Moreover, an Atlas project can utilize the Atlas App Services applications platform to easily integrate many authentication providers such as Google, Facebook, JWT, and custom authentication.
Scaling and managing Atlas is very easy; its biggest benefit is that it supports and secures the MEAN stack's most valuable layer: the data layer.
We recommend using the MEAN stack with MongoDB Atlas, since Atlas has built-in credentials, a firewall, and end-to-end encryption, which is the best foundation for securing your MongoDB.
Additionally, the MEAN stack has a concrete three-tier separation which, if used with best practices and correct network isolation, should prevent your end users from having access to the business logic and, moreover, to your database layer. Therefore, your application is by default designed to avoid malicious user interaction from putting your application at risk (query injection, code manipulation, port spoofing, etc.).
MEAN Stack is a variation of a full stack in that it has:
Although a MEAN stack developer should focus their expertise on the building blocks specific to MongoDB, Express, Angular, and Node, a general full stack developer might need other or more skill sets.
Welcome to the MEAN stack tutorial! This tutorial will teach you how to build a full stack web application using the MEAN stack. The final project will be an employee management system. You can find the source code for this tutorial on Github.
But first things first, let's start with the basics.
MEAN is a technology stack used for building full stack applications. It's a combination of the following technologies:
Applications built with the MEAN stack follow the client-server architecture. The client, built with Angular, can be a web application, a native mobile application, or a desktop application. The client communicates with the server through an API, which is built with Express. The server then manages the requests with the MongoDB database.
Client-Server Architecture
In this tutorial, we'll build a RESTful API that implements the CRUD (Create, Read, Update, Delete) operations for an employee. For data persistence, we'll be using a MongoDB Atlas cluster.
We'll be building an employee management web application. The interface will have the following pages:
Here's what our finished application looks like:
You'll need Node.js and a MongoDB Atlas cluster to follow this tutorial.
node --version
Let's start by creating a directory that will host our project and its files. We'll name it
‘mean-stack-example’
.
mkdir mean-stack-example cd mean-stack-example
We'll be using shell commands to create directories and files throughout the tutorial. However, you're more than welcome to use any other method.
Now, let's create the directories and files that will host our server-side application—
‘server’
and
‘server/src’
—and also initialize a
‘package.json’
file for it.
mkdir server && mkdir server/src cd server npm init -y touch tsconfig.json .env (cd src && touch database.ts employee.routes.ts employee.ts server.ts)
We'll need a few external packages to build the RESTful API and to connect to our MongoDB Atlas cluster. Let's install them using the
npm install
command.
npm install cors dotenv express mongodb
We'll also be using TypeScript for our server application. We'll install the TypeScript compiler and the supporting
@types
packages as development dependencies using the
--save-dev
flag. These packages are only used during development and shouldn't be included in the final production application.
npm install --save-dev typescript @types/cors @types/express @types/node ts-node
Finally, we'll paste the following into the
tsconfig.json
configuration file that TypeScript will use to compile our code.
mean-stack-example/server/tsconfig.json
{ "compilerOptions": { "module": "commonjs", "esModuleInterop": true, "target": "es6", "noImplicitAny": true, "moduleResolution": "node", "sourceMap": true, "outDir": "dist", "baseUrl": ".", "allowJs": true, "paths": { "*": ["node_modules/*"] } }, "include": ["src/**/*"] }
Since we’re building an employee management app, the main data unit is the employee. Let's create an
Employee
interface that will be used to define the structure of the employee object.
mean-stack-example/server/src/employee.ts
import * as mongodb from "mongodb"; export interface Employee { name: string; position: string; level: "junior" | "mid" | "senior"; _id?: mongodb.ObjectId; }
Our employees should have a name, position, and level. The
_id
field is optional because it's generated by MongoDB. So, when we're creating a new employee, we don't need to specify it. However, when we get an employee object from the database, it will have the
_id
field populated.
Let's implement the following function to connect to our database:
mean-stack-example/server/src/database.ts
import * as mongodb from "mongodb"; import { Employee } from "./employee"; export const collections: { employees?: mongodb.Collection
; } = {}; export async function connectToDatabase(uri: string) { const client = new mongodb.MongoClient(uri); await client.connect(); const db = client.db("meanStackExample"); await applySchemaValidation(db); const employeesCollection = db.collection
("employees"); collections.employees = employeesCollection; } // Update our existing collection with JSON schema validation so we know our documents will always match the shape of our Employee model, even if added elsewhere. // For more information about schema validation, see this blog series: https://www.mongodb.com/blog/post/json-schema-validation--locking-down-your-model-the-smart-way async function applySchemaValidation(db: mongodb.Db) { const jsonSchema = { $jsonSchema: { bsonType: "object", required: ["name", "position", "level"], additionalProperties: false, properties: { _id: {}, name: { bsonType: "string", description: "'name' is required and is a string", }, position: { bsonType: "string", description: "'position' is required and is a string", minLength: 5 }, level: { bsonType: "string", description: "'level' is required and is one of 'junior', 'mid', or 'senior'", enum: ["junior", "mid", "senior"], }, }, }, }; // Try applying the modification to the collection, if the collection doesn't exist, create it await db.command({ collMod: "employees", validator: jsonSchema }).catch(async (error: mongodb.MongoServerError) => { if (error.codeName === 'NamespaceNotFound') { await db.createCollection("employees", {validator: jsonSchema}); } }); }
We're using the MongoDB Node.js Driver distributed as the
mongodb
NPM package. First, we create a new
MongoClient
object with the provided connection string. Then, we connect to the database. We need to use
await
since
connect
is an asynchronous function. After that, we get the
db
object from the
client
object. We use this object to get the employees collection. Note that the variable
employees
is cast to the
Employee
interface. This will provide type checking to any query we send to the database. Finally, we assign the employees collection to the
collections
object which is exported from this file. That way, we can access the employees collection from other files such as the
employee.routes.ts
file which will implement our RESTful API.
We're also using JSON schema validation to ensure that all of our documents follow the shape of our
Employee
interface. This is a good practice to ensure that we don't accidentally store data that doesn't match the shape of our model.
We'll be persisting our data to a MongoDB Atlas cluster. To connect to our cluster, we'll need to set an
ATLAS_URI
environment variable that contains the connection string. Add it to the
server/.env
file. Make sure you replace the username and password placeholder with your credentials.
mean-stack-example/server/.env
ATLAS_URI=mongodb+srv://
:@sandbox.jadwj.mongodb.net/meanStackExample?retryWrites=true&w=majority
Now, we can load the environment variables using the
dotenv
package. We can do that in any file but it's a good practice to do it as early as possible. Since the
server.ts
file will be our entry point, let's load the environment variables from it, connect to the database, and start the server:
mean-stack-example/server/src/server.ts
import * as dotenv from "dotenv"; import cors from "cors"; import express from "express"; import { connectToDatabase } from "./database"; // Load environment variables from the .env file, where the ATLAS_URI is configured dotenv.config(); const { ATLAS_URI } = process.env; if (!ATLAS_URI) { console.error("No ATLAS_URI environment variable has been defined in config.env"); process.exit(1); } connectToDatabase(ATLAS_URI) .then(() => { const app = express(); app.use(cors()); // start the Express server app.listen(5200, () => { console.log(`Server running at http://localhost:5200...`); }); }) .catch(error => console.error(error));
Let's run the app and see if everything works:
npx ts-node src/server.ts
You should see the following output:
Server running at http://localhost:5200...
Good job! Now, we’re ready to build the RESTful API for our employees.
In this section, we'll implement a ‘GET’, ‘POST’, ‘PUT’, and ‘DELETE’ endpoint for our employees. As you can notice, these HTTP methods correspond to the CRUD operations— Create, Read, Update, and Delete—we'll be performing on our employees in the database. The only caveat is that we'll have two ‘GET’ endpoints: one for getting all employees and one for getting a single employee by ID.
To implement the endpoints, we'll use the router provided by Express. The file we'll be working in is
src/employee.routes.ts
.
Let's start by implementing the ‘GET /employees’ endpoint which will allow us to get all the employees in the database.
mean-stack-example/server/src/employee.routes.ts
import * as express from "express"; import * as mongodb from "mongodb"; import { collections } from "./database"; export const employeeRouter = express.Router(); employeeRouter.use(express.json()); employeeRouter.get("/", async (_req, res) => { try { const employees = await collections.employees.find({}).toArray(); res.status(200).send(employees); } catch (error) { res.status(500).send(error.message); } });
We're using the
find()
method. Because we're passing in an empty object—
{}
—we'll get all the employees in the database. We'll then use the
toArray()
method to convert the cursor to an array. Finally, we'll send the array of employees to the client.
You may notice that the route is ‘/’. This is because we'll register all endpoints from this file under the ‘/employees’ route.
Next, we'll implement the ‘GET /employees/:id’ endpoint which will allow us to get a single employee by ID. Append the following to the bottom of
employee.routes.ts
:
mean-stack-example/server/src/employee.routes.ts
employeeRouter.get("/:id", async (req, res) => { try { const id = req?.params?.id; const query = { _id: new mongodb.ObjectId(id) }; const employee = await collections.employees.findOne(query); if (employee) { res.status(200).send(employee); } else { res.status(404).send(`Failed to find an employee: ID ${id}`); } } catch (error) { res.status(404).send(`Failed to find an employee: ID ${req?.params?.id}`); } });
The ID of the employee is provided as a parameter. We use the
ObjectId
method to convert the string ID to a MongoDB
ObjectId
object. We then use the
findOne()
method to find the employee with the given ID. If the employee is found, we'll send it to the client. Otherwise, we'll send a ‘404 Not Found’ error.
If you're wondering what the ‘?’ symbol represents in some of the expressions above, it's optional chaining operator. It enables you to read the value of a nested property without throwing an error if the property doesn't exist. Instead of throwing an error, the expression evaluates to
undefined
.
The ‘POST /employees’ endpoint will allow us to create a new employee. Append the following to the bottom of
employee.routes.ts
:
mean-stack-example/server/src/employee.routes.ts
employeeRouter.post("/", async (req, res) => { try { const employee = req.body; const result = await collections.employees.insertOne(employee); if (result.acknowledged) { res.status(201).send(`Created a new employee: ID ${result.insertedId}.`); } else { res.status(500).send("Failed to create a new employee."); } } catch (error) { console.error(error); res.status(400).send(error.message); } });
We receive the employee object from the client in the request body. We'll use the
insertOne()
method to insert the employee into the database. If the insertion is successful, we'll send a ‘201 Created’ response with the ID of the employee. Otherwise, we'll send a ‘500 Internal Server Error’ response.
The ‘PUT /employees/:id’ endpoint will allow us to update an existing employee. Append the following to the bottom of 'employee.routes.ts':
mean-stack-example/server/src/employee.routes.ts
employeeRouter.put("/:id", async (req, res) => { try { const id = req?.params?.id; const employee = req.body; const query = { _id: new mongodb.ObjectId(id) }; const result = await collections.employees.updateOne(query, { $set: employee }); if (result && result.matchedCount) { res.status(200).send(`Updated an employee: ID ${id}.`); } else if (!result.matchedCount) { res.status(404).send(`Failed to find an employee: ID ${id}`); } else { res.status(304).send(`Failed to update an employee: ID ${id}`); } } catch (error) { console.error(error.message); res.status(400).send(error.message); } });
Here, the ID of the employee is provided as a parameter whereas the employee object is provided in the request body. We use the
ObjectId
method to convert the string ID to a MongoDB
ObjectId
object. We then use the
updateOne()
method to update the employee with the given ID. If the update is successful, we'll send a ‘200 OK’ response. Otherwise, we'll send a ‘304 Not Modified’ response.
Finally, the ‘DELETE /employees/:id’ endpoint will allow us to delete an existing employee. Append the following to the bottom of ‘employee.routes.ts’:
mean-stack-example/server/src/employee.routes.ts
employeeRouter.delete("/:id", async (req, res) => { try { const id = req?.params?.id; const query = { _id: new mongodb.ObjectId(id) }; const result = await collections.employees.deleteOne(query); if (result && result.deletedCount) { res.status(202).send(`Removed an employee: ID ${id}`); } else if (!result) { res.status(400).send(`Failed to remove an employee: ID ${id}`); } else if (!result.deletedCount) { res.status(404).send(`Failed to find an employee: ID ${id}`); } } catch (error) { console.error(error.message); res.status(400).send(error.message); } });
Similar to the previous endpoints, we send a query to the database based on the ID passed as a parameter. We use the
deleteOne()
method to delete the employee. If the deletion is successful, we'll send a ‘202 Accepted’ response. Otherwise, we'll send a ‘400 Bad Request’ response. If the employee is not found (
result.deletedCount
is 0), we'll send a ‘404 Not Found’ response.
Now, we need to instruct the Express server to use the routes we've defined. First, import the
employeesRouter
at the beginning of ‘src/server.ts’:
mean-stack-example/server/src/server.ts
import { employeeRouter } from "./employee.routes";
Then, add the following right before the
app.listen()
call:
mean-stack-example/server/src/server.ts
app.use("/employees", employeeRouter);
Finally, restart the server by stopping the shell process with Ctrl-C, and running it again.
npx ts-node src/server.ts
You should see the same message as before in the console.
Server running at http://localhost:5200...
Well done! We've built a simple RESTful API for our employees. Now, let's build an Angular web application to interact with it!
The next step is to build a client-side Angular web application that will interact with our RESTful API. We'll use the Angular CLI to scaffold the application. To install it, open a new terminal tab and run the following command in the terminal from the root of your
mean-stack-example
folder:
npm install -g @angular/cli
It's important to keep the server running while you're working on the client-side application. To do this, you'll need to open a new tab in your terminal where you will execute commands for the client-side application. Also, make sure you navigate to the
mean-stack-example
directory.
After the installation is finished, navigate to the root directory of the project and run the following command to scaffold a new Angular application:
ng new client --routing --style=css --minimal
This will create a new Angular application in the ‘client’ directory. The
--routing
flag will generate a routing module. The
--style=css
flag will enable the CSS preprocessor. The
--minimal
flag will skip any testing configuration as we won't be covering that in the tutorial. Installing the dependencies may take a while. After the installation is finished, navigate to the new application and start it by running the following commands:
cd client ng serve -o
After the application is built, you should see a new tab in your browser window with the application running.
Finally, for styling we'll use Bootstrap. Add the following to section in the ‘src/index.html’ file:
mean-stack-example/client/src/index.html
Client
Similar to our server-side application, we'll create an Angular interface for our employees. We'll use the
Employee
interface to define the properties of our employee objects. Open a new terminal window and run the following command to scaffold the interface:
ng generate interface employee
Then, open the newly create ‘src/app/employee.ts’ file in your editor and add the following properties:
mean-stack-example/client/src/app/employee.ts
export interface Employee { name?: string; position?: string; level?: 'junior' | 'mid' | 'senior'; _id?: string; }
Angular recommends separating your business logic from your presentation logic. That's why we'll create a service that handles all communication with the ‘/employee’ endpoint of the API. The service will be used by the components in the application. To generate the service, run the following command:
ng generate service employee
The ‘ng generate service’ command creates a new service in the ‘src/app/employee.service.ts’ file. Replace the content of this file with the following:
mean-stack-example/client/src/app/employee.service.ts
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable, Subject, tap } from 'rxjs'; import { Employee } from './employee'; @Injectable({ providedIn: 'root' }) export class EmployeeService { private url = 'http://localhost:5200'; private employees$: Subject
= new Subject(); constructor(private httpClient: HttpClient) { } private refreshEmployees() { this.httpClient.get
(`${this.url}/employees`) .subscribe(employees => { this.employees$.next(employees); }); } getEmployees(): Subject
{ this.refreshEmployees(); return this.employees$; } getEmployee(id: string): Observable
{ return this.httpClient.get
(`${this.url}/employees/${id}`); } createEmployee(employee: Employee): Observable
{ return this.httpClient.post(`${this.url}/employees`, employee, { responseType: 'text' }); } updateEmployee(id: string, employee: Employee): Observable
{ return this.httpClient.put(`${this.url}/employees/${id}`, employee, { responseType: 'text' }); } deleteEmployee(id: string): Observable
{ return this.httpClient.delete(`${this.url}/employees/${id}`, { responseType: 'text' }); } }
We're using the
HttpClient
service to make HTTP requests to our API. The
refreshEmployees()
method is used to fetch the full list of employees.
The
HttpClient
service is provided by Angular through the
HttpClientModule
. It's not part of the application by default—we need to import it in the ‘app.module.ts’ file. First, add the following import to the top of the ‘app.module.ts’ file:
mean-stack-example/client/src/app/app.module.ts
import { HttpClientModule } from '@angular/common/http';
Then, add the module to the list of imports of the
AppModule
class:
@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Next, we'll create a new page that displays a table with our employees.
Let's create a new page for our table with employees. In Angular, a component is a reusable piece of code that can be used to display a view. We'll create a new component called
EmployeesList
and then also register it as the ‘/employees’ route in the application.
To generate the component, run the following command:
ng generate component employees-list
The Angular CLI generated a new component named
EmployeesList
in the ‘src/app/employees-list.component.ts’ file. It also declared the component in the ‘AppModule’ so we don’t have to do it manually. Replace the content of ‘src/app/employees-list.component.ts’ with the following:
mean-stack-example/client/src/app/employees-list/employees-list.component.ts
import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs'; import { Employee } from '../employee'; import { EmployeeService } from '../employee.service'; @Component({ selector: 'app-employees-list', template: `MEAN Stack hoạt động như thế nào?
Kiến trúc của MEAN được thiết kế để giúp lập trình viên có thể xây dựng các ứng dụng web bằng ngôn ngữ JavaScript và xử lý JSON một cách dễ dàng.
Người dùng sẽ tương với các component Angular.js UI ở giao diện người dùng của ứng dụng trong trình duyệt. Một máy chủ Express.js viết bằng Node.js sẽ phục vụ cho phần front end. Bất kỳ tương tác nào tạo ra một yêu cầu thay đổi dữ liệu sẽ được gửi đến cho máy chủ Express.js.
Sau đó, máy chủ thu dữ liệu từ cơ sở dữ liệu MongoDB (trong trường hợp được yêu cầu) và đưa lên giao diện người dùng của ứng dụng.
Nguồn tham khảo: https://www.educative.io/edpresso/what-is-mean-stack
Edit an Employee
` }) export class EditEmployeeComponent implements OnInit { employee: BehaviorSubject
= new BehaviorSubject({}); constructor( private router: Router, private route: ActivatedRoute, private employeeService: EmployeeService, ) { } ngOnInit() { const id = this.route.snapshot.paramMap.get('id'); if (!id) { alert('No id provided'); } this.employeeService.getEmployee(id !).subscribe((employee) => { this.employee.next(employee); }); } editEmployee(employee: Employee) { this.employeeService.updateEmployee(this.employee.value._id || '', employee) .subscribe({ next: () => { this.router.navigate(['/employees']); }, error: (error) => { alert('Failed to update employee'); console.error(error); } }) } }
The only notable difference from the
AddEmployeeComponent
is that we're getting the employee ID from the URL, fetching the employee from the API, and then passing it to the form in the
ngOnInit()
method.
Finally, let's add navigation to our new pages:
mean-stack-example/client/src/app/app-routing.module.ts
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { EmployeesListComponent } from './employees-list/employees-list.component'; import { AddEmployeeComponent } from './add-employee/add-employee.component'; // <-- add this line import { EditEmployeeComponent } from './edit-employee/edit-employee.component'; // <-- add this line const routes: Routes = [ { path: '', redirectTo: 'employees', pathMatch: 'full' }, { path: 'employees', component: EmployeesListComponent }, { path: 'employees/new', component: AddEmployeeComponent }, // <-- add this line { path: 'employees/edit/:id', component: EditEmployeeComponent }]; // <-- add this line @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
Alright! Let's test it out! Go ahead and try to create a new employee. After filling in the details, click the Submit button. You should see the new employee on the list. Then, you can try editing it by clicking the Edit button. You should see the form filled with the employee's details. When you submit the form, the employee will be updated in the table. Finally, you can delete it by clicking the Delete button.
If something doesn't add up, you can check out the finished project in the mean-stack-example repository.
Thank you for joining me on this journey and following along! I hope you enjoyed it and learned a lot. The MEAN stack makes it easy to get started and to build scalable applications. You're using the same language throughout the stack: JavaScript. Additionally, MongoDB's document model makes it natural to map data to objects and MongoDB Atlas's forever-free cluster makes it easy to host your data without worrying about costs.
The MEAN stack is a JavaScript-based framework for developing web applications. MEAN is named after MongoDB, Express, Angular, and Node, the four key technologies that make up the layers of the stack.
There are variations to the MEAN stack such as MERN (replacing Angular.js with React.js) and MEVN (using Vue.js). The MEAN stack is one of the most popular technology concepts for building web applications.
The MEAN architecture is designed to make building web applications in JavaScript and handling JSON incredibly easy.
At the very top of the MEAN stack is Angular.js, the self-styled “JavaScript MVW Framework” (MVW stands for “Model View and Whatever”).
Angular.js allows you to extend your HTML tags with metadata in order to create dynamic, interactive web experiences much more powerfully than, say, building them yourself with static HTML and JavaScript (or jQuery).
Angular has all of the bells and whistles you’d expect from a front-end JavaScript framework, including form validation, localization, and communication with your back-end service.
The next level down is Express.js, running on a Node.js server. Express.js calls itself a “fast, unopinionated, minimalist web framework for Node.js,” and that is indeed exactly what it is.
Express.js has powerful models for URL routing (matching an incoming URL with a server function), and handling HTTP requests and responses. By making XML HTTP requests (XHRs), GETs, or POSTs from your Angular.js front end, you can connect to Express.js functions that power your application.
Those functions, in turn, use MongoDB’s Node.js drivers, either via callbacks or using promises, to access and update data in your MongoDB database.
If your application stores any data (user profiles, content, comments, uploads, events, etc.), then you’re going to want a database that’s just as easy to work with as Angular, Express, and Node.
That’s where MongoDB comes in: JSON documents created in your Angular.js front end can be sent to the Express.js server, where they can be processed and (assuming they’re valid) stored directly in MongoDB for later retrieval.
Again, if you want to easily get the best of MongoDB, you’ll want to look at MongoDB Atlas. This will allow you built-in full database security and cross-cloud scalability with the click of a button. More on that later on this page.
MEAN applications can be used in many ways with a cross-platform write-once approach. While MEAN is particularly suited to real-time applications, particularly those running natively in the cloud and single-page (dynamic) web applications built in Angular.js, it can be used for other use cases such as:
There are many more uses for the MEAN stack, as well.
Since all the components are based on JavaScript and JSON, the integration between the components of the stack is intuitive and straightforward.
Additionally, the E and A of MEAN (Express and Angular) are two of the most popular and well-supported JavaScript frameworks for back-end and front-end development, respectively. Express makes routing and managing HTTP requests and responses super easy, and includes great support for middleware to handle JSON endpoints and form posts. Angular is a powerful tool for building dynamic HTML pages that communicate with a back-end server.
Whether you’re building a high-throughput API, a simple web application, or a microservice, MEAN is the ideal stack for building Node.js applications.
All of the MEAN stack components are open source in nature and therefore allow a generous, free-of-charge opportunity for developers.
JavaScript is a great modern language, but it wasn’t initially designed to build back-end servers. Since the foundation of the MEAN stack is JavaScript, including the back-end server, it might come with concurrency and performance problems at scale due to JavaScript nature.
Additionally, since the development opportunity is so rapid, business and server logic might suffer from poor isolation, making potential spaghetti code and bad practices a reality along the way.
Finally, although there are many guides and tutorials out there, they generally will not include concrete JS coding guidelines appropriate for this stack. Therefore, something that worked really well for one application might surface issues for another.
MEAN follows the traditional three-tier stack pattern, including the display tier (Angular.js), application tier (Express.js and Node.js), and database tier (MongoDB).
If you’re building a JavaScript application, particularly in Node.js, then you should give MEAN a serious look.
MongoDB stores data in a JSON-like format (BSON, a binary JSON extension), the MongoDB Query Language (MQL) is defined in JSON, and its command line interface (CLI) is a JavaScript interpreter. Not only is MongoDB essentially a JavaScript/JSON data store, but it’s full of advanced features like indexing and querying deep into JSON documents, has powerful native Node.js drivers, and is designed for horizontal scale-out. It’s even easier to develop apps in the cloud using MongoDB Atlas, the cloud-native database as a service from the creators of MongoDB.
Whether you’re building a high-throughput API, a simple web application, or a microservice, MEAN is the ideal stack for building Node.js applications.
The MongoDB Node.js driver makes working with MongoDB from inside a Node.js script simple and intuitive for developers — saving developers time and increasing their productivity.
Next, you'll need a MongoDB database. The easiest way to get started with MongoDB is to create a free cluster in MongoDB Atlas, MongoDB's fully managed, multi-cloud document database as a service.
Atlas databases are easily deployed and scaled, providing you with a consistent URI to connect. See the official MongoDB documentation on connecting to a cluster.
Along the way, Atlas connections come with built-in username/password and TLS end-to-end encryption by default. Additionally, these connections allow you to utilize advanced MongoDB security features such as certificate/IAM authentication, LDAP, Encryption-at-rest, and Auditing with the click of a button.
Moreover, an Atlas project can utilize the Atlas App Services applications platform to easily integrate many authentication providers such as Google, Facebook, JWT, and custom authentication.
Scaling and managing Atlas is very easy; its biggest benefit is that it supports and secures the MEAN stack's most valuable layer: the data layer.
We recommend using the MEAN stack with MongoDB Atlas, since Atlas has built-in credentials, a firewall, and end-to-end encryption, which is the best foundation for securing your MongoDB.
Additionally, the MEAN stack has a concrete three-tier separation which, if used with best practices and correct network isolation, should prevent your end users from having access to the business logic and, moreover, to your database layer. Therefore, your application is by default designed to avoid malicious user interaction from putting your application at risk (query injection, code manipulation, port spoofing, etc.).
MEAN Stack is a variation of a full stack in that it has:
Although a MEAN stack developer should focus their expertise on the building blocks specific to MongoDB, Express, Angular, and Node, a general full stack developer might need other or more skill sets.
MEAN (solution stack)
MEAN (MongoDB, Express.js, AngularJS (or Angular), and Node.js)[1] is a source-available JavaScript software stack for building dynamic web sites and web applications.[2] A variation known as MERN replaces Angular with React.js front-end,[3][4] and another named MEVN use Vue.js as front-end.
Because all components of the MEAN stack support programs that are written in JavaScript, MEAN applications can be written in one language for both server-side and client-side execution environments.
Though often compared directly to other popular web development stacks such as the LAMP stack, the components of the MEAN stack are higher-level including a web application presentation layer and not including an operating system layer.[5]
The acronym MEAN was coined by Valeri Karpov.[6] He introduced the term in a 2013 blog post and the logo concept, initially created by Austin Anderson for the original MEAN stack LinkedIn group, is an assembly of the first letter of each component of the MEAN acronym.[7]
MongoDB
MongoDB sử dụng một quá trình xử lý để xử lý các yêu cầu về dữ liệu. Quản lý định dạng dữ liệu, thực hiện các hoạt động quản lý bên dưới là mongod. Trong việc mở rộng theo chiều ngang sử dụng mô hình mảnh lưu trữ, MongoDB cung cấp dịch vụ xử lý các truy vấn từ tầng ứng dụng, xác định vị trí dữ liệu trong cụm các node phân mảnh được gọi là mongos.
Xem ngay các việc làm MongoDB
Further reading[edit]
- Haviv, Amos Q. (2014). MEAN Web Development: Master real-time web application development using a mean combination of MongoDB, Express, Angular JS, and Node.js. Birmingham, UK: Packt Publishing. ISBN 978-1783983285.
- Holmes, Simon (2019). Getting MEAN with Mongo, Express, Angular, and Node, Second Edition. Shelter Island, NY: Manning Publishing. ISBN 9781617294754.
- Holmes, Simon (2015). Getting MEAN with Mongo, Express, AngularJs, and Node. Shelter Island, NY: Manning Publishing. ISBN 9781617292033.
- Dickey, Jeff (2014). Write Modern Web Apps with the MEAN Stack: Mongo, Express, AngularJS, and Node.js (Develop and Design). San Francisco, CA: Peachpit Press. ISBN 978-0133930153.
Ưu điểm của việc phát triển ứng dụng web với MEAN Stack
3.Đơn giản hóa việc chuyển đổi giữa máy khách và máy chủ
Với việc phát triển ứng dụng bằng MEAN Stack, lập trình viên sẽ tiết kiệm được rất nhiều thời gian và công sức. Bạn chỉ cần viết code bằng ngôn ngữ duy nhất là JavaScript cho cả máy khách và máy chủ.
3.Có thể code Isomorphic
Chuyển code sang một framework khác được viết bởi một framework cụ thể sẽ dễ dàng hơn với sự hỗ trợ của MEAN Stack.
3.Tính linh hoạt cao
Với MEAN, bạn có thể thực hiện việc kiểm tra ứng dụng trên nền tảng đám mây một cách thuận lợi sau khi đã hoàn thành quy trình phát triển. Đồng thời, MEAN cũng cho phép bạn dễ dàng thêm thông tin bổ sung bằng cách thêm các trường vào biểu mẫu.
3.Tối ưu chi phí
Sử dụng MEAN Stack để phát triển ứng dụng chỉ đòi hỏi các lập trình viên phải thông thạo JavaScript. Trong khi đó, việc dùng LAMP Stack lại cần nhiều hơn thế. Điều này giúp tiết kiệm chi phí thuê và đào tạo nhân công cho các hãng sản xuất công nghệ.
3.Có tốc độ cao và tái sử dụng được
Node.js là có tốc độ xử lý cực nhanh và là một framework có cấu trúc non-blocking. Trong khi đó, Angular.js là một JavaScript framework mã nguồn mở cung cấp khả năng bảo trì, kiểm tra và tái sử dụng.
3.Mã nguồn mở và có khả năng tương thích với đám mây
Toàn bộ công nghệ MEAN Stack đều là mã nguồn mở có sẵn hoàn toàn miễn phí. Vì thế, việc sử dụng MEAN Stack cho phép lập trình viên có nhiều sự lựa chọn với thư viện và các kho lưu trữ công cộng. Nó cũng cho phép giảm chi phí phát triển phần mềm hiệu quả. MongoDB hỗ trợ việc triển khai các chức năng đám mây trong ứng dụng bằng cách giảm chi phí của không gian đĩa.
Sử dụng MEAN Stack sẽ đem lại rất nhiều lợi ích cho bạn trong quá trình phát triển các ứng dụng web. Nếu bạn là một front end developer và muốn tối ưu năng suất làm việc của mình thì hãy dành thêm thời gian tìm hiểu về khái niệm MEAN Stack là gì cũng như cách thức ứng dụng công nghệ này nhé.
https://www.zeolearn.com/magazine/7-advantages-of-developing-apps-with-mean-stack
The mean stack tutorial is designed for the developers who want to design the dynamic website and web application using Mean.js. Our tutorial covers all the components of Mean.js, such as MongoDB, Express.js, Node.js, and Angular.js. The Mean.js can be considered a collection of various technologies for developing a dynamic website and web application. Mean.js is used for developing a web application where MongoDB is used as a database system, Express.js is used as a back-end web framework, node.js is used as a web server, and Angular.js is used as a front-end framework. Each letter in the word MEAN has some specific meaning. Here, 'M' stands for MongoDB, 'E' stands for Express, 'A' stands for Angular, and 'N' stands for Node.js. It is one of the most popular stacks used for developing the full stack application. Let's understand the basic idea behind the mean stack. As we can observe in the above figure that there is a front-end app, back-end app and database. The front-end app can be developed using either Angular.js or React.js, and back-end can be developed using Node.js, which is further connected to the MongoDB database. The front-end app and back-end app communicate with each other through the RestAPI. The back-end app exposes the RestAPI endpoints, whereas the front-end app consumes the RestAPI endpoints. Let's look at each component of Mean.js one by one. Node.js is an open-source platform and provides a runtime environment for executing the javascript code. It is mainly used for building the back-end application. Since there are two types of apps, such as web apps and mobile apps, where web apps run on the browser and mobile apps run on mobile devices. Both web app and mobile app are the client apps to which the user interacts. These apps require to communicate with the backend services to store the data, send emails, push notifications. Node.js is an ideal platform to build highly scalable, data-intensive, and real-time applications. It can be used for agile development and highly-scalable services. For example, PayPal is a java and spring-based application using Node.js. Advantages of Node.js Angular.js is a JavaScript framework that is used to develop web applications. This framework is developed by the Google. Now, the question arises that there are many javascript frameworks available in the market. Why do we prefer angular.js over the other frameworks for developing the web application?. Advantages of Angular.js MongoDB is the database used in web development. It is a NoSQL database, and a NoSQL database can be defined as a non-relational and document-oriented database management system. As it is a document-oriented database management system, so it stores the data in the form of documents. The SQL databases use SQL query language to query the database, whereas the MongoDB is a NoSQL database that uses BSON language to query the database. JSON is a text-based format, but it is inefficient in terms of speed and space. In order to make MongoDB efficient in terms of space and speed, BSON was invented. BSON basically stores the JSON format in the binary form that optimizes the space, speed, and complexity. Since the MongoDB is an unstructured schema and the data is not related to each other then the question arises 'why do we need to use the MongoDB?'. MongoDB is mainly useful for projects which are huge. Express.js is a free and open-source software used as a back-end web application framework. It is commonly used in the popular development stacks like MEAN with a MongoDB database. The Express.js was developed by TJ Holowaychuk. Advantages of Express.js MEAN.js is a framework for designing web applications. The user should have knowledge of web development using HTML, CSS, and JavaScript and should have basic knowledge of all the four technologies which are MongoDB, Express.js, Angular.js, and Node.js. This tutorial is helpful for both beginners and professionals who want to build a career in web-development or seamlessly learn the precepts of MEAN.js. There are a lot of topics and concepts available that will help you to learn MEAN.js easily. We assure you that you will not find any problem with this MEAN Stack tutorial. But if there is any mistake, please post the problem in the contact form. Next TopicArchitecture of MEAN Stack |
Table of content
As a web developer, diving into the world of full-stack development can be both exciting and challenging. One of the popular choices for building robust web applications is the MEAN stack. MEAN stands for MongoDB, Express.js, Angular, and Node.js – a powerful combination of technologies that allows you to create modern, scalable, and efficient web applications.
In this step-by-step tutorial, we will guide you through the process of building a production-ready MEAN stack application. By the end of this tutorial, you will have a solid understanding of how these technologies work together and be ready to start your own MEAN stack project.
Before we begin, ensure that you have the following tools and knowledge:
Now that you have the necessary tools in place, let’s get started with building your MEAN stack application!
1. Create a new directory for your project:
bash mkdir mean-stack-app cd mean-stack-app
2. Initialize your Node.js project:
bash npm init -y
1. Install Express.js, a popular Node.js web application framework:
bash npm install express --save
2. Create a basic Express.js server in a file named `server.js`. This will be your application’s backend:
javascript const express = require('express'); const app = express(); const port = 3000; app.get('/', (req, res) => { res.send('Hello MEAN Stack!'); }); app.listen(port, () => { console.log(`Server is running on port ${port}`); });
3. Start your Node.js server:
bash node server.js
Your server should now be running at `http://localhost:3000`, and you should see “Hello MEAN Stack!” when you visit this URL in your browser.
1. Generate a new Angular project:
bash ng new mean-stack-frontend
Follow the prompts to configure your Angular project.
2. Navigate to your Angular project directory:
bash cd mean-stack-frontend
3. Start the Angular development server:
bash ng serve
Your Angular application will be available at `http://localhost:4200`. Visit this URL in your browser, and you should see the default Angular app.
1. Open the `src/environments/environment.ts` file in your Angular project and update the `apiUrl` property to point to your Express.js server:
typescript export const environment = { production: false, apiUrl: 'http://localhost:3000', };
2. Create an Angular service to interact with your Express.js backend. You can generate a service using the Angular CLI:
bash ng generate service api
Implement your API service to make HTTP requests to your Express.js server.
3. Update your Angular components to use the API service to fetch data from the server and display it in your application.
1. Start your MongoDB server:
bash mongodb
2. Connect your Express.js backend to MongoDB using a MongoDB driver such as Mongoose.
3. Create MongoDB models and routes to handle data storage and retrieval in your Express.js application.
1. Choose a hosting provider for your MEAN stack application. Popular options include Heroku, AWS, and Microsoft Azure.
2. Deploy your Express.js backend and MongoDB to your chosen hosting environment.
3. Deploy your Angular frontend to a hosting service like Netlify, Vercel, or GitHub Pages.
4. Update your Angular `environment.ts` file to point to your production API URL.
Congratulations! You’ve now built and deployed a production-ready MEAN stack application. This tutorial provides a solid foundation for creating web applications using the MEAN stack, but there is still much more to explore and learn. As you gain experience, you can enhance your application with features like user authentication, data validation, and more.
Happy coding, and best of luck with your MEAN stack journey!
Table of content
External links[edit]
- meanjs.org is a fork of mean.io. It uses a tool called 'Yeoman' to generate Angular CRUD, routes, controllers, views, and services.
- Trendnologies Bigdata Course
- MEAN Stack User Registration and Login Tutorial
- Spark Databox MEAN Stack Online Course
- Understanding MERN and MEAN Stack
- FAQs About Hiring MERN Stack Developers
A relatively new stack, MEAN stands for MongoDB, Express.js, AngularJS, and Node.js. MEAN is an end-to-end JavaScript stack largely used for cloud-ready applications. Understanding why you might use it, identifying examples of when to employ it, and diving deeper into the individual components can help you maximize the value of MEAN for software development.
When building an application from scratch, employing a consistent, standardized software stack is vital. Creating your backend with a set of tools designed to work together reduces development time and streamlines resources.
However, the stack field is getting crowded. From LAMP to Ruby on Rails, there are a number of options. Each stack has its benefits and downsides and is geared for different projects. There’s no one-size-fits-all stack for development.
MEAN is an open source web stack that is mainly used to create cloud-hosted applications. MEAN stack applications are flexible, scalable, and extensible, making them the perfect candidate for cloud hosting. The stack includes its own web server so it can be deployed easily, and the database can be scaled on demand to accommodate temporary usage spikes. A MEAN application enters the world optimized to take advantage of all the cost savings and performance improvements of the cloud.
JavaScript has long been a popular language for front-end web development—it’s flexible, dynamic, and easy to use. But it has been an option only for backend and database development for a few years, allowing developers to create applications using end-to-end JavaScript. Because every part of MEAN uses the same language, you can streamline your development teams. MEAN removes the need to hire different specialists to develop each part of an application. Instead, you can use a single pool of JavaScript developers to work adaptively, where and when needed. Standardizing on JavaScript also provides an opportunity to reuse code across the entire application, reducing unnecessary reinvention.
While the MEAN stack isn’t perfect for every application, there are many uses where it excels. It’s a strong choice for developing cloud-native applications because of its scalability and its ability to manage concurrent users. The AngularJS frontend framework also makes it ideal for developing single-page applications (SPAs) that serve all information and functionality on a single page. Here are a few examples for using MEAN:
MongoDBMongoDB is an open source, NoSQL database designed for cloud applications. It uses object-oriented organization instead of a relational model.
In the MEAN stack, MongoDB stores the application’s data. Because both the application and the database use JavaScript, there’s no need to translate the object as it journeys from the application to the database and back. The application can push and pull objects between the back end and the database without missing a beat.
MongoDB is touted for its scalability in both storage and performance. You can add fields to the database without reloading the entire table, and MongoDB is well known for its ability to manage large amounts of data without compromising on data access. With just a few clicks, you can expand the resources available to your database, making it perfect for applications with occasional periods of increased activity.
For a deeper dive into MongoDB, see "MongoDB: An Essential Guide."
ExpressExpress is a web application framework for Node.js. It balances ease of use and a full feature set.
Forming the backend of the MEAN stack, Express handles all the interactions between the frontend and the database, ensuring a smooth transfer of data to the end user. It’s designed to be used with Node.js and so continues the consistent use of JavaScript throughout the stack.
Express is minimalist—it’s designed to efficiently handle processes without cluttering your application. But don’t confuse minimalist with featureless. Express offers excellent error handling and templating functionality to aid your development.
Express can also protect you from yourself because it uses the CommonJS module standard to prevent inadvertent overwriting of variables within the shared namespace. You can’t accidentally redefine a variable that you previously created. This enforcement of JavaScript closures can help prevent a time-consuming and costly error.
AngularJSAngularJS—Google’s JavaScript frontend framework—isn’t the only frontend framework in use, but it’s exceedingly popular. It is effectively the default for frontend JavaScript development. If you’re developing a web application in JavaScript, you’re using AngularJS.
The MEAN stack includes AngularJS to help developers build the user-facing side of the application. Because the backend, frontend and database are all built on JavaScript, there’s a smooth flow of information between all parts of your application.
AngularJS didn’t become the most popular JavaScript frontend framework by mistake. Its ability to simultaneously develop for desktop and mobile use, its well-tuned performance and its easy-to-use templates make it the ideal front end to build cloud-native applications.
Node.jsNode.js is an open source JavaScript framework that uses asynchronous events to process multiple connections simultaneously. It is an ideal framework for a cloud-based application, as it can effortlessly scale requests on demand. You’re likely to find Node.js behind most well-known web presences.
Node.js is the backbone of the MEAN stack. Express is purpose-built to work on top of Node.js, and AngularJS connects seamlessly to Node.js for fast data serving. Node.js comes complete with an integrated web server, making it easy to deploy your MongoDB database and application to the cloud.
The greatest strength of Node.js is its scalability. Cloud applications are best when they can respond quickly to usage spikes. What good is virtually unlimited processing power if it’s only available after your users time out? By expanding your resources as they’re needed, you’re able to serve more users while the framework’s single-thread architecture allows the application to effectively provide a smooth user experience across numerous connections. Node.js can support as many as a million simultaneous connections.
Remember, Node.js works best with many low-resource requests as opposed to resource-intensive requests. While a single thread protects against process deadlocks, it’s not immune to a large process freezing the system for all clients.
IBM Cloud is a leader in cloud-native app development and a trusted partner to build your enterprise apps quickly on an open, secure and integrated platform.
IBM Cloud Infrastructure as a Service is the infrastructure for smarter business. Find the right solutions for your business requirements.
Discover a security-rich, scalable cloud-native platform for your cloud-native application development. For the past 20 years, IBM has invested significantly in open source code, communities and governance, including the Cloud Native Computing Foundation. With more than 20,000 Kubernetes clusters currently in production and running, IBM Cloud is built to deliver. And IBM Cloud provides one of the highest industry standards for data encryption and adheres to more than 30 compliance programs.
MEAN Stack là gì? Với những ai đã và đang làm việc với JavaScript thì chắc hẳn đã từng nghe đến khái niệm này. Bài viết dưới đây sẽ giới thiệu cho mọi người về định nghĩa, cấu trúc và ưu điểm của giải pháp phát triển ứng dụng web này.
Tìm hiểu MEAN Stack là gì?
MEAN Stack là một tập hợp các công nghệ JavaScript được sử dụng để xây dựng các ứng dụng web full-stack. Mỗi chữ cái trong từ “MEAN” đại diện cho một công nghệ cụ thể:
- M: MongoDB là một cơ sở dữ liệu NoSQL dựa trên JSON.
- E: Express.js là một framework web dựa trên Node.js.
- A: Angular là một framework web dựa trên TypeScript.
- N: Node.js là một nền tảng runtime cho JavaScript chạy trên máy chủ.
MEAN Stack cung cấp một giải pháp toàn diện cho việc phát triển ứng dụng web, từ giao diện người dùng (UI) đến cơ sở dữ liệu. Các công nghệ trong MEAN Stack đều được xây dựng dựa trên ngôn ngữ JavaScript, điều này giúp cho việc học hỏi và sử dụng chúng trở nên dễ dàng hơn.
Các thành phần chi tiết của MEAN Stack
MongoDB
Hệ quản trị cơ sở dữ liệu NoSQL, lưu trữ dữ liệu dưới dạng JSON-like (BSON). MongoDB là một cơ sở dữ liệu linh hoạt và có khả năng mở rộng tốt.
Express.js
Framework web cho Node.js, giúp xây dựng và tổ chức ứng dụng web và API. Express cung cấp các tính năng giúp xử lý yêu cầu HTTP, quản lý định tuyến (routing), và nhiều chức năng khác giúp phát triển ứng dụng một cách dễ dàng.
Angular (hoặc AngularJS)
Angular là một framework phía client do Google phát triển. Nó giúp xây dựng giao diện người dùng động và phức tạp thông qua việc sử dụng các thành phần (components) và liên kết dữ liệu hai chiều (two-way data binding).
Node.js
Môi trường thực thi JavaScript ở phía máy chủ, xây dựng trên engine V8 của Google Chrome. Node.js cho phép chạy mã JavaScript ở phía server, giúp đồng bộ hóa mã nguồn ở cả phía client và server.
Kết hợp những công nghệ này tạo ra một bộ công cụ đầy đủ cho việc phát triển ứng dụng web động và hiệu quả. MEAN Stack thường được sử dụng để xây dựng các ứng dụng web đa trang (SPA – Single Page Applications) và ứng dụng web thời gian thực.
MEAN Stack hoạt động như thế nào?
MEAN Stack hoạt động bằng cách kết hợp các thành phần MongoDB, Express.js, Angular (hoặc AngularJS), và Node.js để xây dựng ứng dụng web đa trang (SPA) và ứng dụng web thời gian thực.
Dưới đây là mô tả cách MEAN Stack hoạt động theo các bước cơ bản:
-
Client-Side (Phía Client): Angular (hoặc AngularJS)
- Angular (hoặc AngularJS) chịu trách nhiệm cho giao diện người dùng của ứng dụng.
- Xử lý sự kiện và tương tác người dùng.
- Gửi yêu cầu đến server thông qua HTTP.
-
Server-Side (Phía Server): Node.js và Express.js
- Node.js chạy ở phía server và quản lý các yêu cầu từ phía client.
- Express.js, một framework Node.js, được sử dụng để xây dựng các API RESTful và quản lý các yêu cầu HTTP.
- Xử lý các yêu cầu từ phía client, truy cập cơ sở dữ liệu MongoDB thông qua các truy vấn.
-
Database: MongoDB
- MongoDB, một hệ quản trị cơ sở dữ liệu NoSQL, lưu trữ dữ liệu dưới dạng BSON (Binary JSON).
- Dữ liệu được lưu trữ trong các tài liệu (documents) trong các bảng (collections).
-
Kết nối Client và Server: API RESTful
- Express.js tạo ra các API RESTful để tương tác giữa client và server.
- Các yêu cầu HTTP được gửi từ phía client đến server, và server xử lý yêu cầu này, thực hiện truy vấn cơ sở dữ liệu (nếu cần), và trả về kết quả dưới dạng JSON hoặc các dữ liệu khác.
-
Two-Way Data Binding (Angular):
- Angular (hoặc AngularJS) thực hiện two-way data binding, giúp đồng bộ hóa dữ liệu giữa phía client và server một cách tự động.
- Thay đổi trên giao diện người dùng được tự động cập nhật trong dữ liệu ở phía server và ngược lại.
Kết hợp cả bốn thành phần này tạo ra một quy trình phát triển ứng dụng mạnh mẽ và linh hoạt, cho phép phát triển ứng dụng web đa nền tảng và đa chức năng.
Ưu điểm của MEAN Stack là gì?
MEAN Stack mang lại nhiều ưu điểm cho việc phát triển ứng dụng web, đặc biệt là trong môi trường phát triển đa nền tảng và đa chức năng. Dưới đây là một số ưu điểm chính của MEAN Stack:
- JavaScript toàn diện: MEAN sử dụng JavaScript từ phía client đến phía server, giúp đơn giản hóa quá trình phát triển và tối ưu hóa tương tác giữa các thành phần.
- Dữ liệu JSON chung: Dữ liệu truyền tải giữa client và server đều sử dụng định dạng JSON, giúp tạo sự thống nhất và dễ đọc.
- Real-time Applications: Node.js, một phần của MEAN Stack, hỗ trợ các ứng dụng thời gian thực nhờ vào khả năng xử lý sự kiện và I/O không chặn.
- Môi trường xây dựng đa nền tảng: MEAN Stack cho phép phát triển ứng dụng chạy trên nhiều nền tảng, từ web đến di động, với Angular hỗ trợ xây dựng ứng dụng di động.
- Dễ dàng thay đổi và mở rộng: Các thành phần của MEAN Stack được thiết kế để linh hoạt và mở rộng, giúp dễ dàng thêm các tính năng mới và mở rộng quy mô ứng dụng.
- Community và tài nguyên phong phú: MEAN Stack có một cộng đồng lớn và tích cực, cung cấp nhiều tài nguyên, tư vấn và mã nguồn mở giúp nhà phát triển nhanh chóng giải quyết vấn đề.
- Tích hợp linh hoạt: Các thành phần của MEAN Stack có thể tích hợp với các công nghệ và dịch vụ khác một cách dễ dàng, giúp tối ưu hóa sự đồng nhất và hiệu suất.
- Development Speed: Việc sử dụng JavaScript cho cả phía client và server có thể giúp tăng tốc quá trình phát triển bằng cách chia sẻ mã nguồn và kiến thức giữa các nhóm phát triển.
Nhược điểm của MEAN Stack
- Khả năng hiểu quả trong các trường hợp cụ thể: MEAN không phải lựa chọn tốt nhất cho tất cả các loại ứng dụng và dự án.
- Learning Curve: Việc học và triển khai MEAN Stack có thể đòi hỏi thời gian và kiên nhẫn, đặc biệt là đối với người mới học lập trình.
- Chưa có quy chuẩn chung: Không có quy chuẩn cụ thể hoặc “best practices” cho MEAN Stack, điều này có thể dẫn đến sự khó khăn trong việc lựa chọn và triển khai các thành phần.
- Hiệu suất trong một số trường hợp cụ thể: Hiệu suất của Node.js có thể không phải là lựa chọn tốt nhất đối với mọi loại ứng dụng.
- Security Concerns: Cần phải chú ý đến các vấn đề bảo mật, đặc biệt là khi xử lý dữ liệu và tương tác với cơ sở dữ liệu.
Nhìn lại, MEAN Stack cung cấp một giải pháp đồng nhất và mạnh mẽ cho việc phát triển ứng dụng web, giảm độ phức tạp của việc tích hợp các công nghệ khác nhau và tạo điều kiện thuận lợi cho nhà phát triển.
P.A Việt Nam cung cấp đa dạng các Plan Hosting đáp ứng yêu cầu của khách hàng
Hosting Phổ Thông
Hosting Chất Lượng Cao
Hosting Nodejs
Tham khảo các ưu đãi: https://www.pavietnam.vn/vn/tin-khuyen-mai/
MEAN Stack là gì? Với những ai đã và đang làm việc với JavaScript thì chắc hẳn đã từng nghe đến khái niệm này. Bài viết dưới đây sẽ giới thiệu cho bạn về định nghĩa, cấu trúc và ưu điểm của giải pháp phát triển ứng dụng web này.
Mục lục
- 1. MEAN Stack là gì?
- 2. MEAN Stack hoạt động như thế nào?
- 3. Ưu điểm của việc phát triển ứng dụng web với MEAN Stack
MERN Stack – An Overview
The MERN stack is an acronym for MongoDB, Express.js, React, and Node.js. It is a full-stack JavaScript solution that allows developers to build scalable, high-performance web applications using only one language.
With the MERN stack, developers can create web applications that run seamlessly on both the client and server sides.
Components Of MERN stack
Let’s examine each of the individual components that make up the MERN stack:
MongoDB: A NoSQL database that provides a flexible and scalable way to store and retrieve data. It uses a document-based data model, which makes it ideal for storing unstructured data.
Express.js: A popular web application framework for Node.js, it provides tools and features that make it easy to build scalable and robust web applications.
React: A JavaScript library to build user interfaces, React provides a component-based architecture to create reusable UI components.
Node.js: A JavaScript runtime built on Chrome’s V8 JavaScript engine, Node.js provides an event-driven, non-blocking I/O model ideal for building scalable, high-performance web applications.
If you lack expertise or manpower, you can hire MERN stack developers from reputable IT companies with expertise in MongoDB, Express.js, React, and Node.js.
Let's collaborate with PixelCrayons to bring your vision to life.
Let's collaborate with PixelCrayons to bring your vision to life.
Advantages & Disadvantages Of Using MERN
Like any technology stack, the MERN stack has its advantages and disadvantages. Here are a few to consider:
Advantages:
- Full-stack JavaScript solution
- Scalable and flexible
- Easy to learn and use
- Large developer community
- Fast development time
Disadvantages:
- Limited tooling and libraries
- High memory usage
- Steep learning curve for beginners
- Requires advanced knowledge of JavaScript
Real-world Examples Of MERN
Some popular websites and applications built with the MERN stack include:
- Airbnb
- Uber
- Netflix
Add a New Employee
` }) export class AddEmployeeComponent { constructor( private router: Router, private employeeService: EmployeeService ) { } addEmployee(employee: Employee) { this.employeeService.createEmployee(employee) .subscribe({ next: () => { this.router.navigate(['/employees']); }, error: (error) => { alert("Failed to create employee"); console.error(error); } }); } }
We’re using the
EmployeeForm
, and whenever the
AddEmployeeComponent
receives a form submission, it will call the
EmployeeService
to create the employee. The
EmployeeService
will emit an event when the employee is created and the
AddEmployeeComponent
will navigate back to the table of employees.
While we’re at it, let’s implement the component for editing an employee:
ng generate component edit-employee -m app
Replace the content of the newly created file with the following:
mean-stack-example/client/src/app/edit-employee/edit-employee.component.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { BehaviorSubject } from 'rxjs'; import { Employee } from '../employee'; import { EmployeeService } from '../employee.service'; @Component({ selector: 'app-edit-employee.component.ts', template: `NodeJS
NodeJS là một nền tảng được xây dựng trên “V8 Javascript engine” được viết bằng c++ và Javasccript. Nền tảng này được phát triển bởi Ryan Lienhart Dahl vào năm 2009.
Nếu bạn thành thạo Javascript và muốn tự tay tạo dựng một trang web có tốc độ tải nhanh, lượng truy cập lớn và nhiều tính năng như thương mại điện tử, mạng xã hội…thì sức mạnh của tổ hợp công nghệ này chính là dành cho bạn.
Ngay cả khi bạn chỉ thành thạo một trong các công nghệ trên, thì số lượng công ty săn đón bạn cũng đã cao hơn hẳn, hãy thử tưởng tượng nếu bạn đang là một MEAN Stack developer đa năng thì điều gì sẽ xảy ra? Chắc bạn cũng đoán ra được phần nào.
Bạn có thể tìm hiểu thêm: >>> Việc làm NodeJS lương cao, chất nhất
The mean stack tutorial is designed for the developers who want to design the dynamic website and web application using Mean.js. Our tutorial covers all the components of Mean.js, such as MongoDB, Express.js, Node.js, and Angular.js. The Mean.js can be considered a collection of various technologies for developing a dynamic website and web application. Mean.js is used for developing a web application where MongoDB is used as a database system, Express.js is used as a back-end web framework, node.js is used as a web server, and Angular.js is used as a front-end framework. Each letter in the word MEAN has some specific meaning. Here, 'M' stands for MongoDB, 'E' stands for Express, 'A' stands for Angular, and 'N' stands for Node.js. It is one of the most popular stacks used for developing the full stack application. Let's understand the basic idea behind the mean stack. As we can observe in the above figure that there is a front-end app, back-end app and database. The front-end app can be developed using either Angular.js or React.js, and back-end can be developed using Node.js, which is further connected to the MongoDB database. The front-end app and back-end app communicate with each other through the RestAPI. The back-end app exposes the RestAPI endpoints, whereas the front-end app consumes the RestAPI endpoints. Let's look at each component of Mean.js one by one. Node.js is an open-source platform and provides a runtime environment for executing the javascript code. It is mainly used for building the back-end application. Since there are two types of apps, such as web apps and mobile apps, where web apps run on the browser and mobile apps run on mobile devices. Both web app and mobile app are the client apps to which the user interacts. These apps require to communicate with the backend services to store the data, send emails, push notifications. Node.js is an ideal platform to build highly scalable, data-intensive, and real-time applications. It can be used for agile development and highly-scalable services. For example, PayPal is a java and spring-based application using Node.js. Advantages of Node.js Angular.js is a JavaScript framework that is used to develop web applications. This framework is developed by the Google. Now, the question arises that there are many javascript frameworks available in the market. Why do we prefer angular.js over the other frameworks for developing the web application?. Advantages of Angular.js MongoDB is the database used in web development. It is a NoSQL database, and a NoSQL database can be defined as a non-relational and document-oriented database management system. As it is a document-oriented database management system, so it stores the data in the form of documents. The SQL databases use SQL query language to query the database, whereas the MongoDB is a NoSQL database that uses BSON language to query the database. JSON is a text-based format, but it is inefficient in terms of speed and space. In order to make MongoDB efficient in terms of space and speed, BSON was invented. BSON basically stores the JSON format in the binary form that optimizes the space, speed, and complexity. Since the MongoDB is an unstructured schema and the data is not related to each other then the question arises 'why do we need to use the MongoDB?'. MongoDB is mainly useful for projects which are huge. Express.js is a free and open-source software used as a back-end web application framework. It is commonly used in the popular development stacks like MEAN with a MongoDB database. The Express.js was developed by TJ Holowaychuk. Advantages of Express.js MEAN.js is a framework for designing web applications. The user should have knowledge of web development using HTML, CSS, and JavaScript and should have basic knowledge of all the four technologies which are MongoDB, Express.js, Angular.js, and Node.js. This tutorial is helpful for both beginners and professionals who want to build a career in web-development or seamlessly learn the precepts of MEAN.js. There are a lot of topics and concepts available that will help you to learn MEAN.js easily. We assure you that you will not find any problem with this MEAN Stack tutorial. But if there is any mistake, please post the problem in the contact form. Next TopicArchitecture of MEAN Stack |
“Don’t find customers for your products, find products for your customers.”
– Seth Godin
The same applies to web development. As a developer or enterprise, you must choose the right stack for your project and users. The decision can impact your project’s success, scalability, and flexibility.
MERN and MEAN stacks are two of the most popular stacks for web development. Both stacks have gained significant popularity recently and are used to build robust and scalable web applications.
This post aims to comprehensively compare the MEAN Vs. MERN stacks, highlighting their strengths and weaknesses. We will also offer advice on choosing the right stack for your project, considering various factors.
So, let’s begin!
Table of Contents
To Conclude…
Based on our research on MEAN Vs. MERN, both the stacks have pros and cons; the choice ultimately depends on your enterprise’s specific needs. If you’re building a real-time application, the MERN stack is recommended due to its use of Socket.io.
On the other hand, if you’re building a more traditional web application with developers with Angular expertise, MEAN might be a better fit. We encourage enterprises to define their goals and audience, research different tech stacks, experiment, and continuously monitor and evaluate the chosen stack’s performance and scalability.
So, choose the stack that aligns with your enterprise’s needs and start building your project today.
Get started with our team to stay ahead in the digital landscape.
Get started with our team to stay ahead in the digital landscape.
MEANMERN – Which One To Choose?
Selecting the right tech stack for your web apps is crucial, and factors like development cost, project requirements, scalability, and developer expertise must be considered.
Infowind‘s research shows that over 32% of developers are interested in learning React instead of Angular.
To make an informed decision, enterprises must define their goals, consider their audience, research different stacks, decide, and experiment with the chosen stack to ensure it meets their needs.
Let’s talk about them in the following section in detail.
Factors To Consider
Selecting the right tech stack for your web application is crucial as an enterprise. However, the choice depends on several factors, including:
-
Development Cost
The development cost is a crucial factor that enterprises must consider before choosing a tech stack. MEAN stack, which uses Angular, is slightly more expensive than MERN, which uses React.
Angular is a complete framework and requires more time and resources to learn and implement.
-
Project Requirements
The project’s requirements determine which stack is best suited for the job. If you’re building a real-time application, MERN is the way to go, as it uses Socket.io, which enables real-time communication.
On the other hand, if you’re building a more traditional web application, MEAN might be a better choice.
-
Scalability & Flexibility
Scalability and flexibility are crucial factors that enterprises must consider, especially when building applications that require scaling. Both MERN and MEAN stacks are scalable, but MERN is more flexible. MERN stack uses Node.js, known for its flexibility, and can handle various tasks, including server-side and client-side rendering.
-
Developer Expertise
The expertise of developers working on the project is another essential factor that enterprises must consider. If your developers are familiar with Angular, then MEAN might be a better choice. Similarly, MERN might be better if your developers are proficient in React.
-
New Practices
Lastly, enterprises must consider new practices when selecting a tech stack. MERN stack is relatively new and has gained popularity in recent years. It’s continuously evolving, and new libraries and frameworks are emerging.
On the other hand, the MEAN stack is more established and has a stable ecosystem.
MEAN Stack – An Overview
MEAN stack is another popular technology stack used for full-stack web development.
It stands for MongoDB, Express.js, Angular, and Node.js. MEAN is an open-source, full-stack JavaScript solution that allows developers to create scalable and dynamic web applications.
Components Of MEAN Stack
To better understand the MEAN stack, examining each component closely is essential.
MongoDB: A NoSQL document database for storing data in JSON format.
Express.js: A back-end web application framework for building APIs and web applications.
Angular: A front-end web application framework for building dynamic, single-page applications.
Node.js: A server-side JavaScript runtime environment that allows running JavaScript on the server.
Get ahead with our innovative development team at your side.
Get ahead with our innovative development team at your side.
Advantages & Disadvantages Of Using MEAN
Every technology stack has advantages and disadvantages; the MEAN stack is no exception. Here are a few to consider:
Advantages:
- Complete JavaScript stack for more accessible learning and flexibility
- High scalability and real-time web functionality
- MongoDB database handles large data amounts
- Can build both front-end and back-end components
Disadvantages:
- May not be suitable for simple websites or small-scale apps
- Requires skilled development team
- NoSQL database may not be suitable for all apps
- Potential for performance issues
- More complex and time-consuming to set up
If you plan to develop a MEAN stack application, hire MEAN stack developers to ensure the successful implementation of your project.
Real-world Examples Of MEAN
Here are some real-world examples demonstrating the versatility and effectiveness of the MEAN stack for developing robust and scalable web applications for enterprises.
- PayPal
- Intel
- Accenture
- The Weather Channel
Comparison Of MEAN & MERN Stacks
Let’s take a quick look at the tabular presentation of MEAN stack Vs. MERN stack in the next section:
Parameter |
MERN Stack |
MEAN Stack |
Front-end Framework |
React |
Angular |
Popularity |
Growing in popularity |
More established |
Learning Curve |
Steep for beginners |
Easier to learn |
Performance |
Fast UI rendering |
Better server-side performance |
Scalability |
Good for small to medium-sized apps |
Better for larger and more complex apps |
Community Support |
An active, growing community |
Large and established community |
Which Stack Is Better Suited For Certain Types Of Projects?
Is MEAN stack better than MERN stack? While both stacks offer advantages, the MERN stack may be better suited for projects requiring high interactivity and complex user interfaces, such as eCommerce websites, social media platforms, and real-time chat applications.
MEAN stack is suitable for large-scale enterprise applications that require complex data handling and processing, such as finance applications, healthcare systems, and logistics applications.
It’s important to note that both stacks can be used for various projects. The final decision on which stack to use largely depends on the specific requirements and goals of the project.
How Can PixelCrayons Help You?
PixelCrayons, a reputable MERN stack development company, can help your enterprise as we have:
- Expertise in MEAN and MERN stacks and other popular tech stacks.
- Experienced and certified developers who can help you build your web application from scratch or add new features to your existing application.
- Flexible engagement models to suit your enterprise’s specific needs and budget, including dedicated team, time and material, and fixed price.
- Robust quality assurance processes ensure that your web application is bug-free and meets your enterprise’s requirements.
With over 18 years of experience, PixelCrayons has worked with numerous clients, including startups, SMBs, and enterprises, in various industries such as healthcare, eCommerce, finance, and more. We aim to help your enterprise succeed by providing reliable and innovative web application solutions.
Some of our super-satisfied clients are:
- SimSim
- Fencity
- Book Exchange Place
MEAN Stack là gì?
Được biết đến như là một trong những Technology Stack phổ biến nhất, thuật ngữ MEAN Stack được dùng để chỉ tập hợp các công nghệ dựa trên ngôn ngữ lập trình JavaScript. Chúng được sử dụng để phát triển ứng dụng web full stack. 4 chữ M-E-A-N đại diện cho 4 công nghệ chính cấu thành nên giải pháp này. Mỗi thành phần có một công dụng, cụ thể:
- MongoDB là một cơ sở dữ liệu NoSQL. Nó lưu trữ dữ liệu dưới định dạng JSON định phân nhằm dễ dàng truyền tải dữ liệu giữa server và client.
- Express.js là một web framework được xây dựng trên Node.js. Nó được sử dụng để tạo API và phát triển ứng dụng web.
- Angular.js là một JavaScript Framework dùng để làm front-end cho web, được phát triển bởi Google. Nó kiểm soát hành vi của những phần tử khác nhau được hiển thị trên các trang web.
- Node.js là Java Runtime Environment (JRE), được sử dụng để tạo ra web server.
Angular
Angular là một bộ Javascript Framework rất mạnh và thường được sử dụng để xây dựng project Single Page Application (SPA). Nó hoạt động dựa trên các thuộc tính mở rộng HTML (các atributes theo quy tắc của Angular). Đây là một Framework mã nguồn mở hoàn toàn miễn phí và được hàng ngàn các lập trình viên trên thế giới ưa chuộng và sử dụng.
Xem ngay các việc làm angularjs hấp dẫn
Choosing The Right Tech Stack: A Step-by-Step Process
Selecting the right tech stack for your web application can be challenging. Follow this step-by-step process to determine the most suitable tech stack for your enterprise’s needs.
-
Define Your Goals
Before choosing a tech stack, it’s crucial to define your goals. What kind of web application are you building? What are your business objectives? Addressing these questions lets you narrow your choices and identify your project’s most appropriate tech stack.
-
Consider Your Audience
Another essential factor to consider is your audience. Who are your users? What are their preferences and expectations? Understanding your audience will help you select a tech stack with the best user experience.
-
Research Stacks
Once defining your goals and audience, it’s time to research different tech stacks. MEAN and MERN are popular, but other options, such as LAMP and Django, are available. Research each stack’s strengths, weaknesses, and requirements to determine which aligns with your goals and audience.
-
Make A Decision
After researching the various tech stacks, it’s time to decide. Compare each stack’s features, benefits, and drawbacks against your project’s requirements and audience needs. Consider the development cost, scalability, and developer expertise.
Choose the tech stack that best meets your goals and aligns with your enterprise’s needs.
-
Experiment
Once you have chosen a tech stack, experiment with it to ensure it’s the right choice. Build a prototype or MVP to test its functionality, performance, and scalability.
Get feedback from users and make any essential changes. Continuously monitor and evaluate the tech stack’s performance and scalability to ensure it’s meeting your enterprise’s needs.
Keywords searched by users: mean stack node js
Categories: Khám phá 59 Mean Stack Node Js
See more here: kientrucannam.vn
See more: https://kientrucannam.vn/vn/