• NodeJs连接操作MongoDB数据库


    NodeJs连接操作MongoDB数据库

    一,介绍

    MongoDB是一种文档导向数据库管理系统,由C++撰写而成。介绍如何使用 Node.js 来连接 MongoDB,并对数据库进行操作。

    Mongoose是在node.js异步环境下对mongodb进行便捷操作的对象模型工具。版本:5.4.4

    1. Github地址:https://github.com/Automattic/mongoose
    2. API Docs:http://mongoosejs.com/docs/guide.html

    二,安装配置

    第一步:安装模块

    1 cnpm install mongoose  --save

    第二步:引入模块

    1  // 引入模块
    2 var mongoose=require('mongoose');

    第三步:配置连接

     1 var options = {
     2     db_user: "myAdminUser",//添加的普通账户名
     3     db_pwd: "myAdminPass",
     4     db_host: "127.0.0.1",
     5     db_port: 27017,
     6     db_name: "jackson_YingQi",//数据库名称
     7     useNewUrlParser: true
     8 };
     9 
    10 var dbURL = "mongodb://" + options.db_user + ":" + options.db_pwd + "@" + options.db_host + ":" + options.db_port + "/" + options.db_name;
    11 mongoose.connect(dbURL);// 连接数据库

    连接的方式有

    1. 连接本地数据库服务器,端口是默认的:mongodb://localhost
    2. 使用用户名myAdminUser,密码myAdminPass登录localhost的admin数据库:mongodb://myAdminUser:myAdminPass@localhost
    3. 使用用户名myAdminUser,密码myAdminPass登录localhost的jackson_YingQi数据库:mongodb://myAdminUser:myAdminPass@localhost/jackson_YingQi

    更多连接方式,听查看http://www.runoob.com/mongodb/mongodb-connections.html

    第四步:获取数据库连接句柄

    1 // 得到数据库连接句柄
    2 let dbHandle = mongoose.connection;

    第五步:通过数据库句柄,监听mongoose

    //通过 数据库连接句柄,监听mongoose数据库成功的事件
    dbHandle.on('open', function (err) {
        if (err) {
            console.log('数据库连接失败');
            throw err;
        }
        console.log('数据库连接成功')
    })

    第六步:定义表数据结构table.json

     1 {
     2         "User": {
     3             "title": "String",
     4             "description": "String",
     5             "by": "String",
     6             "url": "String",
     7             "tags": "Array",
     8             "likes": "Number"
     9         }
    10     }

    第七步:表的数据结构和表关联

     1 let MongoDbAction = {}
     2 let filename = path.join(path.dirname(__dirname).replace('app', ''), 'config/table.json');
     3 let tabConf = JSON.parse(fs.readFileSync(path.normalize(filename)));
     4 /**
     5  * 
     6  * @param table_name 表名
     7  */
     8 MongoDbAction.getConnection = function (table_name) {
     9     //定义表数据结构
    10     var userModel = new mongoose.Schema(tabConf[table_name], {
    11         versionKey: false //去除: - -v
    12     })
    13     // 将表的数据结构和表关联起来
    14     // var productModel=mongoose.model('anyname',表的数据结构,表名)
    15     var client = mongoose.model(table_name, userModel, table_name);
    16     return client;
    17 };

    第八步:数据库操作

    常用操作方法,可以查看官方文档

    1,插入数据

    单条:

     1 /**
     2  * 插入单条数据
     3  * @param table_name 表名
     4  * @param insertData 插入的数据
     5  * @param callback 回调方法
     6  */
     7 MongoDbAction.insertData= function (table_name, insertData , callback) {
     8     var node_model = this.getConnection(table_name);
     9     node_model.insertOne(insertData , function (err, res) {
    10         if (err) {
    11             callback(err);
    12         } else {
    13             callback(null, res);
    14         }
    15     });
    16 };

    多条:

     1 /**
     2  * 插入多条数据
     3  * @param table_name 表名
     4  * @param insertData 插入的数据
     5  * @param callback 回调方法
     6  */
     7 
     8 MongoDbAction.insertMany = function (table_name, insertData, callback) {
     9     var node_model = this.getConnection(table_name);
    10     node_model.insertMany(insertData,function(err,res){
    11         if(err){
    12             callback(err);
    13         }
    14         else {
    15             callback(null, res);
    16         }
    17      });
    18 };

    console.log("插入的文档数量为: " + res.insertedCount);res.insertedCount 为插入的条数。 

    2,查询数据

      单条:

     1 /**
     2  * 查询单条数据
     3  * @param table_name 表名
     4  * @param conditions 查询条件
     5  * @param callback 回调方法
     6  */
     7 MongoDbAction.findOne = function (table_name, conditions, callback) {
     8     var node_model = this.getConnection(table_name);
     9     node_model.findOne(conditions, function (err, res) {
    10         if (err) {
    11             callback(err);
    12         } else {
    13             callback(null, res);
    14         }
    15     });
    16 };
     1 /**
     2  * 根据_id查询指定的数据
     3  * @param table_name 表名
     4  * @param _id 可以是字符串或 ObjectId 对象。
     5  * @param callback 回调方法
     6  */
     7 MongoDbAction.findById = function (table_name, _id, callback) {
     8     var node_model = this.getConnection(table_name);
     9     node_model.findById(_id, function (err, res){
    10         if (err) {
    11             callback(err);
    12         } else {
    13             callback(null, res);
    14         }
    15     });
    16 };

      多条:

     1 /**
     2  * 查询数据
     3  * @param table_name 表名
     4  * @param conditions 查询条件
     5  * @param fields 待返回字段
     6  * @param callback 回调方法
     7  */
     8 MongoDbAction.find = function (table_name, conditions, fields, callback) {
     9     var node_model = this.getConnection(table_name);
    10     node_model.find(conditions, fields || null, {}, function (err, res) {
    11         if (err) {
    12             callback(err);
    13         } else {
    14             callback(null, res);
    15         }
    16     });
    17 };
     1 /**
     2  * 连写查询
     3  * @param table_name 表名
     4  * @param conditions 查询条件 {a:1, b:2}
     5  * @param options 选项:{fields: "a b c", sort: {time: -1}, limit: 10}
     6  * @param callback 回调方法
     7  */
     8 MongoDbAction.where = function (table_name, conditions, options, callback) {
     9     var node_model = this.getConnection(table_name);
    10     node_model.find(conditions)
    11         .select(options.fields || '')
    12         .sort(options.sort || {})
    13         .limit(options.limit || {})
    14         .exec(function (err, res) {
    15             if (err) {
    16                 callback(err);
    17             } else {
    18                 callback(null, res);
    19             }
    20         });
    21 };

    返回条数可以使用 limit() 方法,该方法只接受一个参数,指定了返回的条数。

    排序 使用 sort() 方法,该方法接受一个参数,规定是升序(1)还是降序(-1)。

    指定跳过的条数,可以使用 skip() 方法。

     1 /**
     2  * 连接查询 $lookup 来实现左连接。
     3  * @param table_name 表名
     4  * @param conditions 查询条件
     5  * @param callback 回调方法
     6  */
     7 MongoDbAction.findOne = function (table_name, conditions, callback) {
     8     var node_model = this.getConnection(table_name);
     9     node_model.aggregate([
    10     { $lookup:
    11        {
    12          from: 'products',            // 右集合
    13          localField: 'product_id',    // 左集合 join 字段
    14          foreignField: '_id',         // 右集合 join 字段
    15          as: 'orderdetails'           // 新生成字段(类型array)
    16        }
    17      }
    18     ], function (err, res) {
    19         if (err) {
    20             callback(err);
    21         } else {
    22             callback(null, res);
    23         }
    24     });
    25 };

    mongoDB 不是一个关系型数据库,但我们可以使用 $lookup 来实现左连接。

     3,更新数据

    单条:

     1 /**
     2  * 更新单条数据
     3  * @param table_name 表名
     4  * @param conditions 查询条件  {"name":'jackson影琪'}; 
     5  * @param updateStr 更新数据 {$set: { "url" : "https://www.cnblogs.com/jackson-zhangjiang" }};
     6  * @param callback 回调方法
     7  */
     8 MongoDbAction.updateOne= function (table_name, conditions,updateStr , callback) {
     9     var node_model = this.getConnection(table_name);
    10     node_model.updateOne(conditions,updateStr, function (err, res) {
    11         if (err) {
    12             callback(err);
    13         } else {
    14             callback(null, res);
    15         }
    16     });
    17 };

    多条:

     1 /**
     2  * 更新多条数据
     3  * @param table_name 表名
     4  * @param conditions 查询条件  {"type":'1'}; 
     5  * @param updateStr 更新数据 {$set: { "url" : "https://www.cnblogs.com/jackson-zhangjiang" }};
     6  * @param callback 回调方法
     7  */
     8 MongoDbAction.updateMany= function (table_name, conditions,updateStr , callback) {
     9     var node_model = this.getConnection(table_name);
    10     node_model.updateMany(conditions,updateStr, function (err, res) {
    11         if (err) {
    12             callback(err);
    13         } else {
    14            console.log(res.result.nModified + " 条文档被更新");
    15             callback(null, res);
    16         }
    17     });
    18 };

    result.nModified 为更新的条数。

      4,删除数据

    单条:

     1 /**
     2  * 删除单条数据
     3  * @param table_name 表名
     4  * @param conditions 查询条件  {"name":'jackson影琪'}; 
     5  * @param callback 回调方法
     6  */
     7 MongoDbAction.deleteOne= function (table_name, conditions, callback) {
     8     var node_model = this.getConnection(table_name);
     9     node_model.deleteOne(conditions, function (err, res) {
    10         if (err) {
    11             callback(err);
    12         } else {
    13             callback(null, res);
    14         }
    15     });
    16 };

    多条:

     1 /**
     2  * 删除条数据
     3  * @param table_name 表名
     4  * @param conditions 查询条件  {"type":'1'}; 
     5  * @param callback 回调方法
     6  */
     7 MongoDbAction.deleteMany= function (table_name, conditions, callback) {
     8     var node_model = this.getConnection(table_name);
     9     node_model.deleteMany(conditions, function (err, res) {
    10         if (err) {
    11             callback(err);
    12         } else {
    13             console.log(obj.result.n + " 条文档被删除");
    14             callback(null, res);
    15         }
    16     });
    17 };

    obj.result.n 删除的条数。

    以使用 drop() 方法来删除集合

    三,常用方法抛出接口

    以查出一条数据为例,其他的方法类似

    引入

    1 //先包含进来
    2 var MongoDB = require('../services/db_mongodb.js');

    抛出接口

     1 router.put('/user/getSingleData', function (req, res) {
     2     var singleId = req.body.singleId;//'5c4036b04471e7c18ef8f57f'
     3     var tableName = req.body.tableName;//'User'
     4     let data = {
     5         httpCode:200,
     6         message:"查询成功!",
     7         data:null,
     8     }
     9     //查询一条数据
    10 MongoDB.findOne(tableName, {_id:singleId}, function (err, result) {
    11     if(!err){
    12         data.data= result
    13         res.status(data.httpCode).json(data);
    14     }else{
    15         data.httpCode=500
    16         data.message="查询失败!"
    17         data.data= err
    18         res.status(data.httpCode).json(data);
    19     }
    20 });
    21 })

    成功返回的结果

    失败返回的结果

  • 相关阅读:
    Hive窗口函数
    自然周与自然月的Hive统计SQL
    Spark中的Join类型
    随机生成验证码类
    mysql看视频笔记
    sql工作记录
    mysql和sqlserver的区别
    mysql的安装配置
    把一个数组遍历倒序放到另一个数组中,数组取值是c:out value
    Echarts雷达代码
  • 原文地址:https://www.cnblogs.com/jackson-yqj/p/10282074.html
Copyright © 2020-2023  润新知