NodeJS中MongoDB驱动mongodb使用简介
2016-05-17 19:01
691 查看
转自于:http://www.open-open.com/lib/view/open1447489698991.html
虽然说在NodeJS下连接MongoDB用Mongoose的较多,但作为其基础的mongodb库了解一下还是很有必要的。
mongodb库在npmjs的主页:
mongodb
仅仅写了基础的CRUD,详情参考 http://mongodb.github.io/node-mongodb-native/2.0
虽然说在NodeJS下连接MongoDB用Mongoose的较多,但作为其基础的mongodb库了解一下还是很有必要的。
mongodb库在npmjs的主页:
mongodb
安装
一如既往的通过npm安装,命令npm install mongodb连接数据库
通过MongoClient.connect连接数据库,在回调中会返回db对象以供之后使用。var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://localhost:27017/dbname'; MongoClient.connect(url, function(err, db) { if(err){ console.error(err); return; }else{ console.log("Connected correctly to server"); db.close(); } });
获得Collection
调用db对象的collection获得collectionvar collection = db.collection('collectionName');
添加记录
调用collection的insert|insertMany方法添加记录。collection.insert[|insertMangy]({name:"myName",age:"myAge"},function(err,result){ if(err){ console.error(err); }else{ console.log("insert result:"); console.log(result); } })
更新记录
调用collection的updateOne方法更新单个记录。collection.updateOne({ a : 2 }, { $set: { b : 1 } }, function(err, result) { if(err){ console.error(err); }else{ console.log("update result:"); console.log(result); } });
删除记录
调用collection的deleteOne方法更新单个记录。collection.deleteOne({ a : 3 }, function(err, result) { if(err){ console.error(err); }else{ console.log("delete result:"); console.log(result); } });
查询记录
调用collection的find方法查找记录,find方法的参数为查找条件。collection.find({}).toArray(function(err, docs) { if(err){ console.error(err); }else{ console.log("find result:"); console.log(result); } });
仅仅写了基础的CRUD,详情参考 http://mongodb.github.io/node-mongodb-native/2.0
相关文章推荐
- 分享微信开发Html5轻游戏中的几个坑
- 如何在 Fedora 上安装 MongoDB 服务器
- PHP添加yaf xhprof mongodb 同理
- mongodb安装
- 如何在 Ubuntu 上安装 MongoDB
- 信息安全聚合 Sec-News 的重构之路
- 使用ruby部署工具mina快速部署nodejs应用教程
- perl操作MongoDB报错undefined symbol: HeUTF8解决方法
- Google官方支持的NodeJS访问API,提供后台登录授权
- 浅谈Nodejs观察者模式
- nodejs教程之环境安装及运行
- nodejs中的fiber(纤程)库详解
- 基于NodeJS的前后端分离的思考与实践(五)多终端适配
- 基于NodeJS的前后端分离的思考与实践(二)模版探索
- 实例详解Nodejs 保存 payload 发送过来的文件
- 我的NodeJs学习小结(一)
- Node.js 应用跑得更快 10 个技巧
- nodejs中实现sleep功能实例
- Nodejs异步回调的优雅处理方法
- Windows系统下使用Sublime搭建nodejs环境