MongoDB数据库Node.js驱动ES6实战

作者: D6K | 来源:发表于2017-04-10 10:07 被阅读523次

实战准备

开始实战之前,请使用npm init初始化你的项目,然后运行以下命令安装MongoDB驱动及其依赖。
npm install mongodb --save
其依赖包括:

  • mongodb-core
  • bson
  • kerberos
  • bson-ext
  • node-gyp
    其中kerberos和bson-ext是本地C++扩展,属于可选项,并不是驱动必须的。安装出现麻烦了请看Troubleshooting

为什么选择ES6

ES6是JS的未来,她引入了许多新的特性,同时保持与ES5的兼容。MongoDB node.js驱动通过Promise提供了异步方法,为我们优雅地操作MongoDB提供了便利。

连接MongoDB走起

 const MongoClient = require("mongodb").MongoClient,
    co = require("co");
const url = 'mongodb://localhost:23223/dk';

co(function* (){
    var db = yield MongoClient.connect(url);
    // other 
    db.close();
}).catch(onerror);

function onerror(err){
    console.log(err.stack);
}

MongoClient连接方法若没有提供回调则返回Promise对象。以上使用了生成器函数的yield关键字执行MongoClient.connect函数返回的Promise,还使用catch对可能出现的错误进行捕获。

CRUD wtih ES6

插入文档

  • insertOne(doc)
  • insertMany(docs)
const MongoClient = require("mongodb").MongoClient,
    co = require("co");
const url = 'mongodb://localhost:23223/dk'; 

co(function* (){
    var db = yield MongoClient.connect(url),
        users = db.collection("users"),
      // Insert a singal document
       sic = yield users.insertOne({username:"dreamer", password:"king"}); 
      // Insert multiple documents
        mic = yield users.insertMany([{username:"dk1", password:1},{username:"dk2",password:2}]);
    assert.equal(1, sic.insertedCount);
    assert.equal(2,mic.insertedCount);
    console.log(sic.insertedCount, mic.insertedCount);
    db.close();
}).catch(onerror);  

function onerror(err){
    console.log(err.stack);
}

const MongoClient = require("mongodb").MongoClient,
      co = require("co"),
      assert = require("assert");
const url = 'mongodb://localhost:23223/dk';

co(function* (){
    var db = yield MongoClient.connect(url),
        users = db.collection("users");
    var result = yield users.insertOne({
            username: "test",
            password: "test1"
            },{
            w: 'majority',
            wtimeout: 10000,
            serializeFunctions: true,
            forceServerObjectId: true
        });
    console.log(result.insertedCount);
    assert.equal(1, result.insertedCount);
    db.close();
}).catch(onerror);

function onerror(err){
    console.log(err.stack);
}

更新文档

  • updataOne()
  • updateMany()
const MongoClient = require("mongodb").MongoClient,
      co = require("co"),
      assert = require("assert");
const url = 'mongodb://localhost:23223/dk';

function onerror(err){
    console.log(err.stack);
}

co(function* (){
    var db = yield MongoClient.connect(url),
        users = db.collection("users");
    // update a single document
    var usd = yield users.updateOne(
        {username:"dk1"},
        {$set:{password:"123"}}
        );
    console.log(usd.matchedCount,usd.modifiedCount);
   // update mutiple documents
    var umd = yield users.updateMany(
        {username:"test"},
        {$set:{password:"456"}}
        );
    console.log(umd.matchedCount,umd.modifiedCount);
  // upsert a single document
    var usid = yield users.updateOne(
        {username:"nobody"},
        {$set:{password:"nobody"}},
        {upsert: true}
    );
    console.log(usid.matchedCount,usid.upsertedCount);
}).catch(onerror);

删除文档

  • deleteOne()
  • deleteMany()
const MongoClient = require("mongodb").MongoClient,
      co = require("co"),
      assert = require("assert");
const url = 'mongodb://localhost:23223/dk';

function onerror(err){
    console.log(err.stack);
}

co(function* (){
    var db = yield MongoClient.connect(url),
        users = db.collection("users");
    // remove a single document
    var rsd = yield users.deleteOne({username:"nobody"});
    console.log(rsd.deletedCount);
    // remove multiple documents
    var rmd = yield users.deleteMany({username:"test"});
    console.log(rmd.deletedCount);
});

查询并修改、删除或替换文档

  • findOneAndUpdate()
  • findOneAndDelete()
  • findOneAndReplace()
    以上三个方法允许用户修改、删除或替换文档,在其操作期间为保证操作是原子的,因此需要付出写入锁定的代价。
const MongoClient = require("mongodb").MongoClient,
      co = require("co");

const url = 'mongodb://localhost:23223/dk';

function onerror(err){
    console.log(err.stack);
}

co(function* (){
    var db = yield MongoClient.connect(url),
        users = db.collection("users");

    // modify and return the modified document
    var fu = yield users.findOneAndUpdate(
        {username:"dk1"},
        {$set:{password:"321"}},
        {returnOriginal: false,
        upsert: true});
    console.log(fu.value.password);

    //remove and return a document
    var fd = yield users.findOneAndDelete({username:"123"});
    console.log(fd.value);

  // replace and return a document
   var fr = yield users.findOneAndUpdate({username:"456"},{$set:{username:"fr",password:"fr"}});
   console.log(fr.value);
}).catch(onerror);

BulkWrite

const MongoClient = require("mongodb").MongoClient,
      co = require("co");

const url = 'mongodb://localhost:23223/dk';

function onerror(err){
    console.log(err.stack);
}

co(function* (){
    var db = yield MongoClient.connect(url),
        users = db.collection("users");
    var bw = yield users.bulkWrite(
        [
            {insertOne:{document:{username:"bw",password:"12"}}},
            {updateOne:{filter:{username:"fr"},update:{$set:{password:"finder"}},upsert:true}},
            {updateMany:{filter:{username:"dk1"},update:{$set:{password:"1200"},upsert: true}}},
            {deleteOne:{filter:{username:"fr"}}},
            {deleteMany:{filter:{username:"dk1"}}},
            {replaceOne:{filter:{username:"dreamer"},replacement:{password:"978"},upsert: true}}
        ],
        {ordered:true,w:1}
        );
    console.log(
        bw.insertedCount,
        Object.keys(bw.insertedIds).length,
        bw.matchedCount,
        bw.modifiedCount,
        bw.deletedCount,
        bw.upsertedCount
        Object.keys(bw.upsertedIds).length
    );
    db.close();
}).catch(onerror);

查询文档

const MongoClient = require("mongodb").MongoClient,
      co = require("co");

const url = 'mongodb://localhost:23223/dk';

function onerror(err){
    console.log(err.stack);
}

co(function* (){
    var db = yield MongoClient.connect(url),
        users = db.collection("users");

    //get first two documents that match the query
    var find = yield users.find({username:"bw"},{_id:0}).limit(2).toArray();
    console.log(find);

    // iterate over  the cursor
    var cursor = users.find({username:"bw"}).limit(2);
    while(yield cursor.hasNext()){
        var doc = yield cursor.next();
        console.log(doc);
    }
    db.close();
}).catch(onerror);

执行命令

const MongoClient = require("mongodb").MongoClient,
      co = require("co");

const url = 'mongodb://localhost:23223/dk';

function onerror(err){
    console.log(err.stack);
}

co(function* (){
    var db = yield MongoClient.connect(url),
        // use the admin database for the operation
        admindb = db.admin();
    // retrive the build infomation using the admin command
    yield admindb.command({buildInfo:1});
    db.close();
}).catch(onerror);

相关文章

网友评论

  • Yard:node版本升级下可以把co模块去掉了
    D6K:@Yard 嗯嗯!是的

本文标题:MongoDB数据库Node.js驱动ES6实战

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