Node.js package operation MongoDB library

In the past, we used Node.js to operate the MongoDB database as follows:

Node.js finds the MongoDb database collection:

MongoClient .connect( dbUrl ,function(err,db){  
        if(err){ /* 数据库连接失败 */  
           console .log('数据库连接失败');         
           return;     
        }  
        var result=[];  
        var userRel=db.collection('user').find();  
        //res.send(userRel);  
        userRel.each(function(err, doc) {         
            if(err){             
                res.write("游标遍历错误");             
                return;         
            }         
            if (doc != null) {             
                result.push(doc);         
            } else {             
                console .log(result);             
                // 遍历完毕             
                db.close();             
                res.render("index",{                 
                    "result" : result             
                });         
            }     
        });  
    })

Node.js adds data to MongoDb:

MongoClient .connect( dbUrl ,function(err,db){     
        if(err){         
            return     
        }     
        db.collection('user').insertOne({         
            "name" : name,         
            "age" : age,         
            "score" : {            
                "shuxue" : shuxuechengji,             
                "yuwen" : yuwenchengji         
            }     
        },function(err,result){         
            if(err){             
                console .log('写入数据失败');         
            }         
            // 关闭数据库         
            db.close();         
            //res.redirect('/add');         
            res.redirect('/');   /* 路由跳转 */         
            res.end();         ////res.location('/add')    
         })  
    })

Node.js modify MongoDb data:

MongoClient .connect( dbUrl ,function(err,db){     
    if(err){         
        console .log('数据库连接错误');         
        return;     
    }     
    db.collection('user').updateOne({"_id": ObjectID (id)}, 
        {  
            "name": name,         
            "age": age,         
            "score": { 
                "shuxue": shuxue,             
                "yuwen": yuwen         
            }     
        },function (err, results) {         
            console .log(results);         
            db.close();  
            res.redirect('/');   /* 路由跳转 */         
            res.end('end');     
        }) 
    }) 

Node.js delete MongoDb data:

MongoClient .connect( dbUrl ,function(err,db){     
        if(err){         
            throw new Error("数据库连接失败");         
            return;     
        }     
        db.collection('user').deleteOne({"_id": ObjectID (id)},function(error,result){         
            if(error){             
                throw  new  Error('删除数据失败');            
                return;         
            }         
            db.close();         
            res.redirect('/');   /* 路由跳转 */     
        }) 
    }) 

We can find that no matter the operation, addition, deletion, modification and query need to connect to the database once, resulting in a lot of repeated code. Next, we need to encapsulate these operations into several simple methods.

We can find that when we operate the database to add, delete, modify and query, we first connect to the database and then perform the corresponding add, delete, modify and query operations, so first we extract the MongoBD database connection:

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

    var DbUrl='mongodb://localhost:27017/test';  /*连接数据库*/


    function  __connectDb(callback){


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

            if(err){

                console.log('数据库连接失败');
                return;
            }
            //增加 修改 删除

              callback(db);

        })

    }

We have extracted the part of connecting to the database. The only difference is that the operation requirements after connecting to the database are different. It may be adding or modifying, deleting, or searching. So we pass a callback method to our __connectDb method . This callback corresponds to our add, modify, delete, and search operations. After waiting for the MongoClient.connect connection to complete, we can call back our callback method.

Next, we implement our addition, deletion, modification and query operations respectively:

Find the implementation of the method :

    exports.find=function(collectionname,json,callback){

        __connectDb(function(db){


            var result=db.collection(collectionname).find(json);

            result.toArray(function(error,data){

                db.close();/*关闭数据库连接*/
                callback(error,data);/*拿到数据执行回调函数*/
            })

        })

    }

Add the implementation of the method :

//增加数据
    exports.insert=function(collectionname,json,callback){

        __connectDb(function(db){


            db.collection(collectionname).insertOne(json,function(error,data){

                callback(error,data);
            })
        })

    }

Modify the implementation of the method :

//修改数据
    exports.update=function(collectionname,json1,json2,callback){

        __connectDb(function(db){
            db.collection(collectionname).updateOne(json1,{$set:json2},function(error,data){

                callback(error,data);
            })
        })

    }

Implementation of delete method :

//删除数据
    exports.deleteOne=function(collectionname,json,callback){

        __connectDb(function(db){
            db.collection(collectionname).deleteOne(json,function(error,data){
                callback(error,data);
            })
        })

    }

This completes our simple MongoDB operation library.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325806239&siteId=291194637