美文网首页
在nodeJS中使用MongoDB

在nodeJS中使用MongoDB

作者: 咔簌 | 来源:发表于2019-06-27 10:49 被阅读0次

(该代码仅作为参考例子使用,路由为自定义的模拟express框架路由)

index.js

var http=require('http');

var ejs=require('ejs');

const MongoClient = require('mongodb').MongoClient;

var app=require('./express-route.js');

var url=require('url');

const dbUrl = 'mongodb://127.0.0.1:27017';

/* 创建服务 */
http.createServer(app).listen(3000);

/* 增加数据 */
app.get('/add',function(req,res){
//连接数据库  mgdemo:数据库名称;student:集合名称
    MongoClient.connect(dbUrl, function(err, client) {
        if(err){
            console.log("数据库连接失败");
            return false;
        }
        var db=client.db('mgdemo');
        
        db.collection('student').insertOne({"name":"zhangsan","age":29},(error,result)=>{
            if(error){
                console.log("增加数据失败");
                return false;
            }
            
            res.send("增加数据成功");

            client.close();
        })
    });
        
})

/* 修改数据 */
app.get('/edit',function(req,res){
    MongoClient.connect(dbUrl, function(err, client) {
        if(err){
            console.log("数据库连接失败");
            return false;
        }
        var db=client.db('mgdemo');

        db.collection("student").updateOne({"name":"zhangsan"},{$set:{"age":90}},(error,result)=>{
            if(error){
                console.log("修改数据失败");
                return false;
            }
            res.send('数据修改成功');
            client.close();
        })
    })
    
})

/* 删除数据 */
app.get("/delete",function(req,res){
    MongoClient.connect(dbUrl,(err,client)=>{

        if(err){
            console.log("数据库连接失败");
            return false;
        }

        
        let query=url.parse(req.url,true).query;

        var db=client.db('mgdemo');
        db.collection('student').deleteOne(query,(error,result)=>{
            if(error){
                console.log("数据删除失败");
                return false;
            }

            res.send("数据删除成功");
            client.close();
            
        })
    })
})

/* 查询数据 */
app.get("/",function(req,res){
    MongoClient.connect(dbUrl,(err,client)=>{

        if(err){
            console.log("数据库连接失败");
            return false;
        }

        var db=client.db('mgdemo');
        var userRel=db.collection('student').find();

            
        var list=[];
        userRel.each((error,col)=>{
            if(error){
                console.log("数据读取失败");
                return false;
            }else{
                if(col!=null){
                    list.push(col);
                }else{
                    //ejs渲染模板
                    ejs.renderFile('./index.ejs',{list},(err,data)=>{
                        res.send(data);
                    })
                }
            }
            client.close();
        })

    })
})

express-route.js

var url=require('url');

//封装方法end
function changeRes(res){

    res.send=function(data){

        res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"});

        res.end(data);
    }
}

//暴露的模块
var Server=function(){

    var G=this;   /*全局变量*/

    //处理get和post请求
    this._get={};
    this._post={};


    var app=function(req,res){
        changeRes(res);

        //获取路由
        var pathname=url.parse(req.url).pathname;
        if(!pathname.endsWith('/')){
            pathname=pathname+'/';
        }

        //获取请求的方式 get  post
        var method=req.method.toLowerCase();

        if(G['_'+method][pathname]){

            if(method=='post'){ /*执行post请求*/

                var postStr='';

                req.on('data',function(chunk){
                    postStr+=chunk;
                })

                req.on('end',function(err,chunk) {

                    req.body=postStr; 

                    G['_'+method][pathname](req,res); /*执行方法*/

                })

            }else{ /*执行get请求*/
                G['_'+method][pathname](req,res); /*执行方法*/
            }

        }else{
            res.end('no router');
        }
    }

    app.get=function(string,callback){
        if(!string.endsWith('/')){
            string=string+'/';
        }
        if(!string.startsWith('/')){
            string='/'+string;

        }

        //    /login/
        G._get[string]=callback;
    }

    app.post=function(string,callback){
        if(!string.endsWith('/')){
            string=string+'/';
        }
        if(!string.startsWith('/')){
            string='/'+string;

        }
       
        G._post[string]=callback;
   }

    return app;
}

module.exports=Server();

index.ejs

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <title></title>
</head>
<body>

    <h2>这是一个ejs的后台模板引擎</h2>
    <ul>
      <% for(var i=0;i<list.length;i++){%>
        <li><%= list[i].name %></li>
      <%}%>
    </ul>

</body>
</html>

相关文章

网友评论

      本文标题:在nodeJS中使用MongoDB

      本文链接:https://www.haomeiwen.com/subject/mwjlcctx.html