node连接mongo对其进行简单的增删改

代码如下

/**
1.npm install mongodb --save-dev / cnpm install mongodb --save-dev

2.var MongoClient = require('mongodb').MongoClient;

 var url = 'mongodb://localhost:27017/test';   连接数据库的地址

 3.连接数据库

 MongoClient.connect(url, function(err, db) {

});

 4.实现增加修改删除

 MongoClient.connect(url, function(err, db) {

    db.collection('user').insertOne({'name':'zhangsan'},function(error,data){




    })

});





 */
var http=require('http');

var ejs=require('ejs');

var MongoClient = require('mongodb').MongoClient;  /*引入数据库 MongoClient*/

var DBurl = 'mongodb://localhost:27017/test';  // 连接数据库的地址   student表示数据库的名称

var url=require('url'); /*引入url模块*/
var app=require('./model/express-route.js');

http.createServer(app).listen(3000);


app.get('/',function(req,res){
    var msg='这是数据库的数据'
    ejs.renderFile('views/index.ejs',{msg:msg},function(err,data){
        res.send(data);
    })

})



app.get('/add',function(req,res){
   //增加数据

    MongoClient.connect(DBurl,function(err,db){  /*连接数据库*/

        if(err){

            console.log(err);
            console.log('数据库连接失败');
            return;
        }

        //增加数据

        db.collection('test').insertOne({

            "name":"李四",
            "age":10

        },function(error,result){
            if(error){

                console.log('增加数据失败');
                return;
            }
            res.send('增加数据成功');
            db.close();/*关闭数据库*/
        })



    })
})




app.get('/edit',function(req,res){
    //增加数据

    //res.send('修改数据成功');


    MongoClient.connect(DBurl,function(err,db){

        if(err){

            console.log(err);
            console.log('数据库连接失败');
            return;
        }

        db.collection('test').updateOne({"name":'lisi'},{$set:{
            "age":666
        }},function(error,data){
            if(error){

                console.log('修改数据失败');
                return;
            }

            console.log(data);
            res.send('修改数据成功');
            db.close();/*关闭数据库*/

        })



    })

})


app.get('/delete',function(req,res){

    var query=url.parse(req.url,true).query;
    var name=query.name;


    MongoClient.connect(DBurl,function(err,db){

        if(err){

            console.log(err);
            console.log('数据库连接失败');
            return;
        }

        db.collection('test').deleteOne({"name":"lisi"},function(error,data){

            if(error){

                console.log('删除失败');
                return;
            }

            console.log(data);
            res.send('删除数据成功');
            db.close();

        })


    })




})


app.get('/test',function (req,res) {
    console.log('这个是test');
    res.send('这个是end')
})

附上app

var url=require('url');

//封装方法改变res  绑定res.send()
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;  /*表示拿到post的值*/


                    //G._post['dologin'](req,res)

                    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;

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

        //G._post['dologin']=function(req,res){
        //
        //}
    }

    return app;

}

module.exports=Server();

 

posted on 2018-02-22 21:34  另一种失败 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/qiaohong/p/8460190.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Node.js中连接MongoDB,你需要使用官方提供的MongoDB驱动程序。以下是一些基本步骤: 1. 首先,确保已经安装了Node.js和MongoDB,并且MongoDB服务器正在运行。 2. 在你的项目文件夹中,通过运行以下命令安装MongoDB驱动程序: ``` npm install mongodb ``` 3. 在你的代码中,导入MongoDB模块并创建一个MongoDB客户端实例。示例代码如下: ```javascript const { MongoClient } = require('mongodb'); // MongoDB连接URL const url = 'mongodb://localhost:27017'; // 创建一个新的MongoDB客户端实例 const client = new MongoClient(url); ``` 请注意,这里使用了本地主机地址和默认端口号27017作为示例。你可以根据你的设置进行。 4. 接下来,你可以使用`connect`方法连接数据库。示例代码如下: ```javascript client.connect(function(err) { if (err) { console.error('连接数据库失败:', err); return; } console.log('成功连接数据库'); // 连接成功后,你可以执行其他操作,如插入、查询等。 }); ``` 5. 当不再需要连接时,记得使用`close`方法关闭连接。示例代码如下: ```javascript client.close(function(err) { if (err) { console.error('关闭数据库连接失败:', err); return; } console.log('数据库连接已关闭'); }); ``` 这只是连接MongoDB的基本步骤,你还可以执行其他操作,如插入数据、查询数据等。你可以查阅MongoDB驱动程序的文档以获取更多详细信息和示例代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值