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

前端之家收集整理的这篇文章主要介绍了node.js操作mongodb简单示例分享前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

首先安装nodejs mongodb

代码

//连接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);
// });

  1. // console.log(collection);
  2. // <a href="/tag/chaxun/" target="_blank" class="keywords">查询</a>数据
  3. var tmp1 = {title:'hello'};
  4. var tmp2 = {title:'world'};
  5. collection.insert([tmp1,tmp2],result){
  6. console.log(result);
  7. });
  8. collection.find().toArray(function(err,docs){
  9. console.log('find');
  10. console.log(docs);
  11. });
  12. collection.findOne(function(err,doc){
  13. console.log('findOne');
  14. console.log(doc);
  15. });
  16. }
  17. });
  18. // console.log('delete ...');
  19. // //<a href="/tag/shanchu/" target="_blank" class="keywords">删除</a>Collection
  20. // db.dropCollection('mycoll',result){

// if(err){

  1. // console.log('err:');
  2. // console.log(err);
  3. // }else{
  4. // console.log('ok:');
  5. // console.log(result);
  6. // }

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

猜你在找的Node.js相关文章