第八天 nodejs下对mongodb数据库的增删改查操作

1、连接数据库及测试

 var mongodb = require('mongodb');
 var server = new mongodb.Server('localhost',27017,{auto_reconnect:true});
 var db = new mongodb.Db('mydb',server,{safe:true});
 db.open(function(err,db){
     if(!err)
     {   
         console.log('connect');
     }else{
         console.log(err);
     }   

 });

2、增加一条记录

 var mongodb = require('mongodb');
 var server = new mongodb.Server('localhost',27017,{auto_reconnect:true});
 var db = new mongodb.Db('mydb',server,{safe:true});
 db.open(function(err,db){
     if(!err)
     {   
       db.collection('mycoll',{safe:true},function(err,collection){
           var tmp1 = {title:'hello',number:1};
           collection.insert(tmp1,{safe:true},function(err,result){
               console.log(result);
           });
     });
     }else{
         console.log(err);
     }   

 });

3、删除一条记录

 var mongodb = require('mongodb');
 var server = new mongodb.Server('localhost',27017,{auto_reconnect:true});
 var db = new mongodb.Db('mydb',server,{safe:true});
 db.open(function(err,db){
     if(!err)
     {
       db.collection('mycoll',{safe:true},function(err,collection){
           collection.remove({title:'hello'},{safe:true},function(err,result){
               console.log(result);
           });

     }else{
         console.log(err);
     }         

 });

4、update

 var mongodb = require('mongodb');
 var server = new mongodb.Server('localhost',27017,{auto_reconnect:true});
 var db = new mongodb.Db('mydb',server,{safe:true});
 db.open(function(err,db){
     if(!err)
     {
       db.collection('mycoll',{safe:true},function(err,collection){
           collection.update({title:'hello'},{$set:{number:3}},{safe:true},function(err,result){
               console.log(result);
           });

     }else{
         console.log(err);
     }

 });

5、作业:

用express写个增删改查的页面

你可能感兴趣的:(第八天 nodejs下对mongodb数据库的增删改查操作)