微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

node.js操作mongodb简单示例分享

前两篇文章我们介绍了nodejs操作redisMysqL,下面简要测试一下nodejs操作mongodb:

首先安装nodejs mongodb

rush:bash;"> npm install mongodb

代码

rush:js;"> var mongodb = require('mongodb'); var server = new mongodb.Server('localhost',27017,{auto_reconnect:true}); var db = new mongodb.Db('mydb',server,{safe:true});

//连接db
db.open(function(err,db){
if(!err){
console.log('connect db');
// 连接Collection(可以认为是MysqL的table)
// 第1种连接方式
// db.collection('mycoll',{safe:true},function(err,collection){
// if(err){
// console.log(err);
// }
// });
// 第2种连接方式
db.createCollection('mycoll',collection){
if(err){
console.log(err);
}else{
//新增数据
// var tmp1 = {id:'1',title:'hello',number:1};
// collection.insert(tmp1,result){
// console.log(result);
// });
//更新数据
// collection.update({title:'hello'},{$set:{number:3}},result){
// console.log(result);
// });
// 删除数据
// collection.remove({title:'hello'},result){
// console.log(result);
// });

    // console.log(collection);
    // <a href="https://www.jb51.cc/tag/chaxun/" target="_blank" class="keywords">查询</a>数据
    var tmp1 = {title:'hello'};
      var tmp2 = {title:'world'};
      collection.insert([tmp1,tmp2],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 ...');
// //<a href="https://www.jb51.cc/tag/shanchu/" target="_blank" class="keywords">删除</a>Collection
// db.dropCollection('mycoll',result){

// if(err){

//     console.log('err:');
//     console.log(err);
//   }else{
//     console.log('ok:');
//     console.log(result);
//   }

// });
}else{
console.log(err);
}
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐