node.js连接mongodb

作者: 风慕李 | 来源:发表于2017-12-08 10:22 被阅读99次

    看此篇文章前如若你不了解也不会简单运用mongodb请戳这里
    1.安装mongodb依赖,这里我们安装v2.2.33版本,如果之前有遇到过db.collection is not function 其实只是mongodb库版本的问题(桌面建立fml文件)

    我的项目文件名为fml
    C:\Users\admin\Desktop\fml> npm install mongodb@2.2.33
    

    2.插入数据
    在fml中新建node-mongodb.js,并复制黏贴下面代码

    var MongoClient = require('mongodb').MongoClient;
    // 连接数据库 字符串形式
    var DB_CONNECT_STR = 'mongodb://localhost:27017/fengml'; 
    var insertData = function(db, callback) {  
        //连接到表 fmlsite
        var collect = db.collection('fmenglsite');
        //插入数据
        var data = [{"author":"风慕李","url":"http://www.jianshu.com/u/96432503edfd","description":"good good study"}];
        collect.insert(data, function(err, result) { 
            if(err){
                console.log('Error:'+ err);
                return;
            }     
            callback(result);
        });
    }
    MongoClient.connect(DB_CONNECT_STR, function(err, db) {
        console.log("connect server success!");
        insertData(db, function(result) {
            console.log(result);
            db.close();
        });
    });
    

    如若你也是vscode的使用者,快捷键Ctrl+`执行node node-mongodb.js

     C:\Users\admin\Desktop\fml> node node-mongodb.js
    connect server success!
    { result: { ok: 1, n: 1 },
      ops:
       [ { author: '风慕李',
           url: 'http://www.jianshu.com/u/96432503edfd',
           description:'good good study',
           _id: 5a28ffd2241ba235a4d51535 } ],
      insertedCount: 1,
      insertedIds: [ 5a28ffd2241ba235a4d51535 ] }
    

    你也可以通过mongodb客户端使用show dbs等语法查看(忘记了就戳这里
    3.查询数据

    var MongoClient = require('mongodb').MongoClient;
    var DB_CONNECT_STR = 'mongodb://localhost:27017/fengml';  
    var searchData = function(db, callback) {  
      //连接到表  
      var collection = db.collection('fengmlsite');
      //查询数据
      var dataStr = {"description":'good good study'};
      collection.find(dataStr).toArray(function(err, result) {
        if(err){
          console.log('Error:'+ err);
          return;
        }    
        callback(result);
      });
    }
    MongoClient.connect(DB_CONNECT_STR, function(err, db) {
      console.log("connect server success");
      searchData(db, function(result) {
        console.log(result);
        db.close();
      });
    });
    

    结果打印(如果返回为[],或许你需要等待一会,或者)

    C:\Users\admin\Desktop\fml> node node-search.js
    connect server success
    [ { _id: 5a2907838e6f0939908741a9,
        author: '风慕李',
        url: 'http://www.jianshu.com/u/96432503edfd',
        description: 'good good study' } ]
    

    4.更新数据

    var MongoClient = require('mongodb').MongoClient;
    var DB_CONNECT_STR = 'mongodb://localhost:27017/fengml';
    var updateData = function(db, callback) {  
        //连接到表  
        var collection = db.collection('fengmlsite');
        //更新数据
        var dataStr = {"author":'风慕李'};
        var updateStr = {$set: { "description" : "day day up" }};
        collection.update(dataStr,updateStr, function(err, result) {
            if(err){
                console.log('Error:'+ err);
                console.log(0)
                return;
            }     
            callback(result);
        });
    }
     MongoClient.connect(DB_CONNECT_STR, function(err, db) {
        console.log("connect server success");
        updateData(db, function(result) {
            console.log(result);
            db.close();
        });
    });
    

    终端输入

    C:\Users\admin\Desktop\fml> node node-update.js
    我们重新运行node-search.js会发现结果为空,我们在将node-search.js的查询条件datastr改为 {"author":'风慕李'}。你会看到如下结果:
    C:\Users\admin\Desktop\fml> node node-search.js
    connect server success
    [ { _id: 5a2907838e6f0939908741a9,
        author: '风慕李',
        url: 'http://www.jianshu.com/u/96432503edfd',
        description: 'day day up' } ]
        这时你会看到description字段已经被更新了
    

    5.删除数据

    var MongoClient = require('mongodb').MongoClient;
    var DB_CONNECT_STR = 'mongodb://localhost:27017/fengml';    
     var delData = function(db, callback) {  
      //连接到表  
      var collection = db.collection('fengmlsite');
      //删除数据
      var dataStr = {"author":'风慕李'};
      collection.remove(dataStr, function(err, result) {
        if(err){
          console.log('Error:'+ err);
          return;
        }     
        callback(result);
      });
    }
     
    MongoClient.connect(DB_CONNECT_STR, function(err, db) {
      console.log("connect server success!");
      delData(db, function(result) {
        console.log(result);
        db.close();
      });
    });
    

    终端输入

    C:\Users\admin\Desktop\fml> node node-delete.js
    我们重新运行node-search.js会发现结果为空,说明删除成功了
    

    注:开始前记得运行mongodb服务(手动运行mongod.exe和mongo.exe或者用命令
    PS:如此一来,前端就可以愉快的操作数据库了,对于前端的我们来说开心不言而喻。

    原文地址 https://gitee.com/wangFengJ/node/tree/master/node-mongodb

    相关文章

      网友评论

        本文标题:node.js连接mongodb

        本文链接:https://www.haomeiwen.com/subject/sxzsixtx.html