前兩篇文章我們介紹了nodejs操作redis和MySQL,下面簡(jiǎn)要測(cè)試一下nodejs操作mongodb:
首先安裝nodejs mongodb
npm install mongodb
代碼
var mongodb = require('mongodb');var server = new mongodb.Server('localhost', 27017, {auto_reconnect:true});var db = new mongodb.Db('mydb', server, {safe:true});//連接dbdb.open(function(err, db){  if(!err){    console.log('connect db');    // 連接Collection(可以認(rèn)為是mysql的table)    // 第1種連接方式    // db.collection('mycoll',{safe:true}, function(err, collection){    //   if(err){    //     console.log(err);    //   }    // });    // 第2種連接方式    db.createCollection('mycoll', {safe:true}, function(err, collection){      if(err){        console.log(err);      }else{        //新增數(shù)據(jù)        // var tmp1 = {id:'1',title:'hello',number:1};    //     collection.insert(tmp1,{safe:true},function(err, result){    //       console.log(result);    //     });           //更新數(shù)據(jù)          // collection.update({title:'hello'}, {$set:{number:3}}, {safe:true}, function(err, result){          //   console.log(result);          // });          // 刪除數(shù)據(jù)            // collection.remove({title:'hello'},{safe:true},function(err,result){    //          console.log(result);    //        });        // console.log(collection);        // 查詢數(shù)據(jù)        var tmp1 = {title:'hello'};          var tmp2 = {title:'world'};          collection.insert([tmp1,tmp2],{safe:true},function(err,result){          console.log(result);          });           collection.find().toArray(function(err,docs){          console.log('find');          console.log(docs);          });           collection.findOne(function(err,doc){          console.log('findOne');           console.log(doc);          });       }    });    // console.log('delete ...');    // //刪除Collection    // db.dropCollection('mycoll',{safe:true},function(err,result){ //      if(err){            //     console.log('err:');    //     console.log(err);    //   }else{    //     console.log('ok:');    //     console.log(result);    //   } //    });   }else{    console.log(err);  }});新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注