


Node.js connects to mongoDB database to quickly build your own web service_node.js
1. Write in front
Everyone wants to be a full-stack coder. As a web front-end developer, the simple way to full-stack seems to be node.js. I learned node.js some time ago, and let’s talk about how novices can quickly build their own web services and start the full-stack journey.
2. Install node.js
Anyone who has been exposed to back-end development knows that the service must be installed first. As a novice, you must choose the simplest visual installation (the next step is fool-proof, other methods will come naturally after you are familiar with the relevant operations), through the official website http://nodejs.org/dist/v0. 6.1/node-v0.6.1.msi Download the computer-adapted installation package (this is for windows, I can’t afford a mac), and then install it according to the boot. By default, it is installed under the C:Program Filesnodejs file. And add this directory to the PATH environment variable. To do this, right-click "My Computer" - "Properties" - "System Advanced" - "Advanced" - "Environment Variables" - select "Variable Name: PATH"; "Change Value: Add [C:Program" at the end Filesnodejs] (depending on your own installation directory)". Open cmd and run the command directly:
node -v can output the current version number. npm has been integrated into the node file, and then use npm install XXX to install the required plug-ins or modules.
3. Use express framework
After working for a while, I finally used the npm command to initialize, install the express framework, and then write hello world. It felt great. Why should you choose express framework? Of course it has its special features. The biggest fear for novices is that it is troublesome and easy to make mistakes. Of course express has taken this into consideration for us, so it provides a quick generator: express-generator
1. Use the command: npm install express-generator -g to install it globally
2. Use express command to generate project structure
express myapp where myapp is your project name
3. Enter the project file via cd myapp
Initialize dependent modules via npm install
Start the web server via set DEBUG=myapp & npm start
4. Open the http://localhost:3000/ URL in the browser to see the application.
The template engine used by default is jade, and this template has been configured in the project.
4. Introducing the express generator project
1. The organization of the myapp project is as follows:
2. package.json This can be said to be the module management package, project information and module version number. In fact, you will find that it is generated by the configuration here when the project module is initialized.
3. app.js is the startup file of the project, which can be said to be the core of the project. Mainly write some public functions.
4. There is a www file without suffix under the bin file. This is the entry file of the project and configures the web service port and some monitoring events.
5. node_modules is the file module that the project depends on, and the packages imported later will also be placed in it, such as the mongoose module that connects to the database, which will be discussed in detail later.
6. Public is the static resource file set of the project. It is easy to see that pictures, css files, and js files are placed here.
7. Routes is the routing module of the project, in which the index.js and user.js files are already defaulted. In fact, this also includes the controller content in the general background language. Of course, it can be separated in large projects.
8. Views is the template file of the project, which is the jade template engine. This template is very simple, but it also has many pitfalls. For example, the requirements for spaces are very strict. If there is one more space or one less space, an error will be reported. I have stepped on many Pitfalls, in fact, its performance is not very high, so it is better to use ejs.
5. Install mongoDB
1. Also download the msi file directly on the official website (http://www.mongodb.org/downloads)
2. Simply proceed to the next step to install. If there is a default, let it be the default. If there is a choice, select all.
3. Then configure the environment variables, which are the same as node and will not be described again, but you can put the middle picture, hahaha...
4. The next step is to start the mongoDB service
5. Pass the command: mongod --dbpath f:MongoDBdata where f:MongoDBdata is the file storage path. If you see the following information, it means success
6. MongoDB listens to port 27017. At the same time, open the browser and enter http://127.0.0.1:27017, you will see the following prompt:
It looks like you are trying to access MongoDB over HTTP on the native driver port.
7. Then, open a cmd and enter the mongo command to connect to the database. The following prompt will appear:
2015-05-02T17:10:19.467+0800 I CONTROL Hotfix KB2731284 or later update is not installed, will zero-out data files MongoDB shell version: 3.0.2 connecting to: test
8. In this way, monogDB in the windows environment is successfully installed.
Supplement:
9. If you find it troublesome to use a command to open the service every time, you can write a batch file, that is, create a new file with the suffix .bat and write the following code:
start mongod --dbpath F:MongoDBdata
10. Of course, you can also start MongoDB as a service, but I think it is not very useful in the learning process. You can try it yourself. If necessary, I will make up for it later. .
11. If you find the command line difficult to use, I recommend a software with a graphical interface: MongoVUE, which is similar to navicat. It has a free version, which has fewer functions, but it is enough for the learning process
6. Using monogDB in node projects
1. Import the monogDB connection module. Express officially introduces the mongoskin module. I won’t go into this. Here is an introduction to installing it through mongoose
2. Execute the command npm install mongoose -save under the myapp project to save the installation to node_modules. You can also configure "mongoose": "^4.4.12" in package.json, and then command npm install to install.
3. In the app.js file
a. Import the mongoose module:
var mongoose = require('mongoose');
b. Create database connection
mongoose.connect('mongodb://localhost/myDB') //Connect to local database
4. Create a new folder schemas in the project root directory. This is the data set module. Create a new users.js file under the module
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
|
5. Add the modules file in the root directory. This is the data model module. Add the users.js file under the module
1 2 3 4 5 |
|
6. Add the routing controller code to the users.js file in the routes file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
7. Add users.jade under the views file
1 2 3 4 5 6 7 8 9 |
|
8. Finally, open the URL in the browser: http://localhost:3000/users/users to check the effect. At this point, a project from database to front-end display is completed.
The above is the entire content of this article, I hope it will be helpful to everyone’s study.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
