MongDB系列(一):使用node.js连接数据库

1、首先启动mongodb数据库服务器

2、创建app.js,代码如下:

 1 /**
 2  * Created by byzy on 2016/8/18.
 3  * node.js 连接 mongodb实例
 4  */
 5 
 6 //引入模块
 7 var express = require('express');
 8 var MongoClient = require('mongodb').MongoClient;
 9 
10 //实例化express
11 var app = express();
12 
13 //设置路由
14 app.get('/', function (req,res) {
15     //连接数据库
16     var url = 'mongodb://127.0.0.1:27017/mytest'; //设置连接的url
17 
18     //连接
19     MongoClient.connect(url, function (err,db) {
20         if(err)
21         {
22             console.log('数据库连接失败');
23             return false;
24         };
25 
26         console.log('数据库连接成功');
27         //在user集合里面写入一条数据
28         db.collection('user').insertOne({
29             'name':'Tom',
30             'age': parseInt(Math.random()*100)+10
31         }, function (err,result) {
32             if(err)
33             {
34                 console.log('插入失败');
35                 return false;
36             };
37 
38             //输出数据库操作结果
39             res.send(result);
40 
41             //关闭链接
42             db.close();
43         });
44     });
45 });
46 
47 //设置监听端口
48 app.listen(3000,'127.0.0.1', function () {
49     console.log('server is started listen is 3000 port');
50 });

3、写入数据成功

技术交流群:821039247
原文地址:https://www.cnblogs.com/humaotegong/p/5784474.html