zoukankan      html  css  js  c++  java
  • nodeCZBK-笔记2

    day04

    mongoDB数据库使用

    1. 电脑全局安装数据库

    2. 开机命令mongod --dbpath c:mongo;

      1. --dbpath 就是选择数据库文档所在的文件夹, 也就是说,mongoDB中,真的有物理文件(开机后文件夹会多出很多文件),对应一个个数据库。U盘可以拷走(.ns文件)。
      2. 一定要保持,开机这个CMD不能动了,不能ctrl+c打断。
    3. 管理数据库 : mongo
      应该再开一个cmd输入mongo;

    4. 数据库命令

      1. 列出所有数据库:show dbs
      2. 使用某个数据库: use 数据库名字
      3. 新建:use一个不存在的,就是新建。
        -- 必须插入一个数据,这个数据库才真创建成功
      4. 查看当前所在数据库: db
      5. 删除当前所在的数据库: db.dropDatabase()
    5. 插入数据

      1. 数据库中不能直接插入数据,只能往集合(collections)中插入数据。不需要创建集合,只需要写点语法:
        db.student.insert({“name”:”xiaoming”})
        
        db.student 系统发现student是一个陌生的集合名字,所以就自动创建此集合。
      2. 导入数据库:
        mongoimport --db aaa --collection bbb --drop --file primer-dataset.json
        
        --db aaa  想往哪个数据库里面导入  
        --collection bbb  想往哪个集合中导入  
        --drop 把集合清空  
        --file primer-dataset.json  导入哪个文件
        
    6. 查找数据 db.restaurants.find()

      1. find中没有参数,那么将列出这个集合的所有文档
      2. 精确匹配:db.student.find({"score.shuxue":70});
      3. 多个条件:db.student.find({"score.shuxue":70 , "age":12})
      4. 大于条件:db.student.find({"score.yuwen":{$gt:50}});
      5. 或者:寻找所有年龄是9岁,或者11岁的学生
        db.student.find({$or:[{"age":9},{"age":11}]});
      6. 排序:查找完毕之后,打点调用sort,表示升降排序。
        db.restaurants.find().sort( { "borough": 1, "address.zipcode": -1 } )
    7. 修改数据
      修改里面还有查询条件。你要改谁,要告诉mongo。

      1. 查找名字叫做小明的,把年龄更改为16岁:
        db.student.update({"name":"小明"},{$set:{"age":16}});
      2. 更改所有匹配项目:
        db.student.update({"sex":"男"},{$set:{"age":33}},{multi: true});
      3. 完整替换整条数据:不出现$set关键字了
        db.student.update({"name":"小明"},{"name":"大明","age":16});
    8. 删除集合 db.students.drop()

    9. 删除数据

      1. 默认都删:
        db.restaurants.remove( { "borough": "Manhattan" } )
      2. 只删一条;
        db.restaurants.remove( { "borough": "Queens" }, { justOne: true } )

    day05

    node使用mongoDB数据库

    var express = require("express");
    var app = express();
    var MongoClient = require('mongodb').MongoClient;
    
    app.get("/",function(req,res){
    
        // url就是数据库的地址.
        // 假如数据库不存在,没有关系,程序会帮你自动创建一个数据库
        var url = 'mongodb://localhost:27017/haha';
        // **连接数据库
        MongoClient.connect(url, function(err, db) {
            //回调函数表示连接成功做的事情,db参数就是连接上的数据库实体
            if(err){
                console.log("数据库连接失败");
                return;
            }
            //插入数据,集合如果不存在,也没有关系,程序会帮你创建
            db.collection('student').insertOne({
                "name" : "哈哈",
                "age" : parseInt(Math.random() * 100 + 10)
            }, function(err, result) {
                if(err){
                    console.log("插入失败");
                    return;
                }
                //插入之后做的事情,result表示插入结果。
                //console.log(result);
                res.send(result);
                db.close();
            });
        });
    });
    
    app.listen(3000);  
    

    封装DAO

    // setting.js
    module.exports = {
        "dburl" : "mongodb://localhost:27017/haha"
    }
    
    
    //这个模块里面封装了所有对数据库的常用操作
    var MongoClient = require('mongodb').MongoClient;
    var settings = require("../settings.js");
    //不管数据库什么操作,都是先连接数据库,所以我们可以把连接数据库
    //封装成为内部函数
    function _connectDB(callback) {
        var url = settings.dburl;   //从settings文件中,都数据库地址
        //连接数据库
        MongoClient.connect(url, function (err, db) {
            if (err) {
                callback(err, null);
                return;
            }
            callback(err, db);
        });
    }
    
    //插入数据
    exports.insertOne = function (collectionName, json, callback) {
        _connectDB(function (err, db) {
            db.collection(collectionName).insertOne(json, function (err, result) {
                callback(err, result);
                db.close(); //关闭数据库
            })
        })
    };
    
    //查找数据,找到所有数据。args是个对象{"pageamount":10,"page":10}
    exports.find = function (collectionName, json, C, D) {
        var result = [];    //结果数组
        if (arguments.length == 3) {
            //那么参数C就是callback,参数D没有传。
            var callback = C;
            var skipnumber = 0;
            //数目限制
            var limit = 0;
        } else if (arguments.length == 4) {
            var callback = D;
            var args = C;
            //应该省略的条数
            var skipnumber = args.pageamount * args.page || 0;
            //数目限制
            var limit = args.pageamount || 0;
            //排序方式
            var sort = args.sort || {};
        } else {
            throw new Error("find函数的参数个数,必须是3个,或者4个。");
            return;
        }
    
        //连接数据库,连接之后查找所有
        _connectDB(function (err, db) {
            var cursor = db.collection(collectionName).find(json).skip(skipnumber).limit(limit).sort(sort);
            cursor.each(function (err, doc) {
                if (err) {
                    callback(err, null);
                    db.close(); //关闭数据库
                    return;
                }
                if (doc != null) {
                    result.push(doc);   //放入结果数组
                } else {
                    //遍历结束,没有更多的文档了
                    callback(null, result);
                    db.close(); //关闭数据库
                }
            });
        });
    }
    
    //删除
    exports.deleteMany = function (collectionName, json, callback) {
        _connectDB(function (err, db) {
            //删除
            db.collection(collectionName).deleteMany(
                json,
                function (err, results) {
                    callback(err, results);
                    db.close(); //关闭数据库
                }
            );
        });
    }
    
    //修改
    exports.updateMany = function (collectionName, json1, json2, callback) {
        _connectDB(function (err, db) {
            db.collection(collectionName).updateMany(
                json1,
                json2,
                function (err, results) {
                    callback(err, results);
                    db.close();
                });
        })
    }
    
    exports.getAllCount = function (collectionName,callback) {
        _connectDB(function (err, db) {
            db.collection(collectionName).count({}).then(function(count) {
                callback(count);
                db.close();
            });
        })
    }
    
  • 相关阅读:
    【leetcode】416. Partition Equal Subset Sum
    【leetcode】893. Groups of Special-Equivalent Strings
    【leetcode】892. Surface Area of 3D Shapes
    【leetcode】883. Projection Area of 3D Shapes
    【leetcode】140. Word Break II
    【leetcode】126. Word Ladder II
    【leetcode】44. Wildcard Matching
    【leetcode】336. Palindrome Pairs
    【leetcode】354. Russian Doll Envelopes
    2017.12.22 英语面试手记
  • 原文地址:https://www.cnblogs.com/topyang/p/7834117.html
Copyright © 2011-2022 走看看