nodeJs 封装一个操作mongodb数据库的插件

nodeJs 封装一个操作mongodb数据库的插件

操作mongoDB数据库需要下载模块

npm install mongodb --save

// 封装一个mongodb数据库增删改查的插件

// 1.引入mongodb模块

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

// 2.mongodb数据库连接url

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

// 3.mongodb数据库名称

const dbName = 'cake';

// 4. 处理mongodb数据的唯一ID

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

// 5.mongdb连接数据库
function connectDb(callback){
    
    
    MongoClient.connect(url,{
    
     useUnifiedTopology: true },(err,client)=>{
    
    
        if (err) {
    
    
            console.log(err);
            console.log('mongodb数据库连接失败');
            return;
        }
        const db = client.db(dbName);
        console.log('mongodb数据库连接成功');
        callback(db,client);
    });
}

// 6. 暴露 ObjectID
module.exports.ObjectID = ObjectID;

// 7. 暴露查询数据
module.exports.find = function(collectionName,json,callback){
    
    
    /*  
    * collectionName:表名
    * json:查询条件,它是json对象,没有值默认为{}
    * callback:返回查询的数据
    */
   connectDb((db,client)=>{
    
    
        let result = db.collection(collectionName).find(json);
        result.toArray((err,data)=>{
    
    
            if (err) {
    
    
                console.log(err);
                return;
            }
            // 关闭数据库连接
            client.close();
            // 返回查询到的数据,执行回调函数
            callback(data);
        });
   });
};

// 8. 暴露插入数据
module.exports.insert = function(collectionName,json,callback){
    
    
    /* 
    collectionName:表名
    json:插入的数据,它是一个json对象,没有值默认为{}
    callback: 返回查询的数据
    */
    connectDb((db,client)=>{
    
    
  
      db.collection(collectionName).insertOne(json,(err,data)=>{
    
    
        if (err) {
    
    
          console.log(err);
          return;
        }
        callback(data);
      });
  
    });
};

// 9. 暴露修改数据
module.exports.update = function(collectionName,json1,json2,callback){
    
    
    /* 
    collectionName:表名
    json1:条件,它是一个json对象,没有值默认为{}
    json2:修改的数据,它是一个json对象,没有值默认为{}
    callback: 返回查询的数据
    */
    connectDb((db,client)=>{
    
    
  
      db.collection(collectionName).updateOne(json1,{
    
    $set:json2},(err,data)=>{
    
    
        if (err) {
    
    
          console.log(err);
          return;
        }
        callback(data);
      });
  
    });
};

// 10. 暴露删除数据
module.exports.delete = function(collectionName,json,callback){
    
    
    /* 
    collectionName:表名
    json:条件,它是一个json对象,没有值默认为{}
    callback: 返回查询的数据
    */
    connectDb((db,client)=>{
    
    
  
      db.collection(collectionName).deleteOne(json,(err,data)=>{
    
    
        if (err) {
    
    
          console.log(err);
          return;
        }
        callback(data);
      });
  
    });
};

猜你喜欢

转载自blog.csdn.net/weixin_45028704/article/details/108678725