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);
}
});

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...