search
HomeWeb Front-endJS TutorialNode.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

var mongoose = require('mongoose');

//申明一个mongoons对象
var UsersSchema = new mongoose.Schema({
 name: String,
 paw: String,
 meta: { 
  createAt: {
   type: Date,
   default: Date.now()
  },
  updateAt: {
   type: Date,
   default: Date.now()
  }
 }
})

//每次执行都会调用,时间更新操作
UsersSchema.pre('save', function(next) {
 if(this.isNew) {
  this.meta.createAt = this.meta.updateAt = Date.now();
 }else {
  this.meta.updateAt = Date.now();
 }

 next();
})

//查询的静态方法
UsersSchema.statics = {
 fetch: function(cb) { //查询所有数据
  return this
   .find()
   .sort('meta.updateAt') //排序
   .exec(cb) //回调
 },
 findById: function(id, cb) { //根据id查询单条数据
  return this
   .findOne({_id: id})   
   .exec(cb)
 }
}

//暴露出去的方法
module.exports = UsersSchema 

5. Add the modules file in the root directory. This is the data model module. Add the users.js file under the module

 var mongoose = require('mongoose')
 var UsersSchema = require('../schemas/users') //拿到导出的数据集模块
 var Users = mongoose.model('Users', UsersSchema) // 编译生成Movie 模型
 
 module.exports = Users

6. Add the routing controller code to the users.js file in the routes file

var express = require('express');
var mongoose = require('mongoose');//导入mongoose模块

var Users = require('../models/users');//导入模型数据模块

var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
 res.send('respond with a resource');
});

//查询所有用户数据
router.get('/users', function(req, res, next) {
 Users.fetch(function(err, users) {
  if(err) {
   console.log(err);
  }  
  res.render('users',{title: '用户列表', users: users}) //这里也可以json的格式直接返回数据res.json({data: users});
 })
})
module.exports = router;

7. Add users.jade under the views file

extends layout

block content
 h1= title //jade取值方式
 ul
 each user in users //jade模版的遍历方式
  li
  h4 #{user.name} 
  span #{user.paw}


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.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment