使用Nodejs连接mongodb数据库的实现代码


Posted in NodeJs onAugust 21, 2017

一个简单的nodejs连接mongodb示例,来自 mongodb官方示例

1. 创建package.json

首先,创建我们的工程目录connect-mongodb,并作为我们的当前目录

mkdir connect-mongodb
cd connect-mongodb

输入npm init命令创建package.json

npm init

然后,安装mongodb的nodejs版本driver

npm install mongodb --save

mongodb驱动包将会安装到当前目录下的node_modules中

2. 启动MongoDB服务器

安装MongoDB并启动MongoDB数据库服务,可参考我之前的文章,或者MongoDB官方文档

3. 连接MongoDB

创建一个app.js文件,并添加以下代码来连接服务器地址为192.168.0.243,mongodb端口为27017上名称为myNewDatabase的数据库

var MongoClient = require('mongodb').MongoClient,
  assert = require('assert');
// Connection URL
var url = 'mongodb://192.168.0.243:27017/myNewDatabase';
MongoClient.connect(url,function(err,db){
  assert.equal(null,err);
  console.log("Connection successfully to server");
  db.close();
});

在命令行输入以下命令运行app.js

node app.js

4. 插入文档

在app.js中添加以下代码,使用insertMany方法添加3个文档到documents集合中

var insertDocuments = function(db, callback){
  // get ths documents collection
  var collection = db.collection('documents');
  // insert some documents
  collection.insertMany([
    {a:1},{a:2},{a:3}
  ],function(err,result){
    assert.equal(err,null);
    assert.equal(3,result.result.n);
    assert.equal(3,result.ops.length);
    console.log("Inserted 3 documents into the collection");
    callback(result);
  });
};

insert命令返回一个包含以下属性的对象:

  • result MongoDB返回的文档结果
  • ops 添加了_id字段的文档
  • connection 执行插入操作所使用的connection

在app.js更新以下代码调用insertDocuments方法

var MongoClient = require('mongodb').MongoClient
 , assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
 assert.equal(null, err);
 console.log("Connected successfully to server");
 insertDocuments(db, function() {
  db.close();
 });
});

在命令行中使用node app.js运行

5. 查询所有文档

添加findDocuments函数

var findDocuments = function(db,callback){
  // get the documents collection
  var collection = db.collection('documents');
  // find some documents
  collection.find({}).toArray(function(err,docs){
    assert.equal(err,null);
    console.log("Found the following records");
    console.log(docs);
    callback(docs);
  });
};

findDocuments函数查询了所有'documents'集合中所有的文档,将此函数添加到MongoClient.connect的回调函数中

var MongoClient = require('mongodb').MongoClient
 , assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
 assert.equal(null, err);
 console.log("Connected correctly to server");
 insertDocuments(db, function() {
  findDocuments(db, function() {
   db.close();
  });
 });
});

6. 使用过滤条件(query filter)查询文档

查询'a':3的文档

var findDocuments = function(db, callback) {
 // Get the documents collection
 var collection = db.collection('documents');
 // Find some documents
 collection.find({'a': 3}).toArray(function(err, docs) {
  assert.equal(err, null);
  console.log("Found the following records");
  console.log(docs);
  callback(docs);
 });   
}

7. 更新文档

var updateDocument = function(db,callback){
  // get the documents collection
  var collection = db.collection('documents');
  // update document where a is 2, set b equal to 1
  collection.updateOne({a:2},{
    $set:{b:1}
  },function(err,result){
    assert.equal(err,null);
    assert.equal(1,result.result.n);
    console.log("updated the document with the field a equal to 2");
    callback(result);
  });
};

updateDocument方法更新满足条件a为2的第一个文档,新增一个b属性,并将其设置为1。

将updateDocument方法添加到MongoClient.connect方法的回调中

MongoClient.connect(url,function(err,db){
  assert.equal(null,err);
  console.log("Connection successfully to server");
  insertDocuments(db,function(){
    updateDocument(db,function(){
      db.close();
    });
  });
});

8. 删除文档

var removeDocument = function(db,callback){
  // get the documents collection
  var collection = db.collection('documents');
  // remove some documents
  collection.deleteOne({a:3},function(err,result){
    assert.equal(err,null);
    assert.equal(1,result.result.n);
    console.log("removed the document with the field a equal to 3");
    callback(result);
  });
};

添加到app.js中

var MongoClient = require('mongodb').MongoClient
 , assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
 assert.equal(null, err);
 console.log("Connected successfully to server");
 insertDocuments(db, function() {
  updateDocument(db, function() {
   removeDocument(db, function() {
    db.close();
   });
  });
 });
});

9. 创建索引

索引能够改善应用的性能。下面你代码在'a'属性上添加索引

var indexCollection = function(db,callback){
  db.collection('documents').createIndex({
    a:1
  },null,function(err,results){
    console.log(results);
    callback();
  });
};

更新app.js

MongoClient.connect(url,function(err,db){
  assert.equal(null,err);
  console.log("Connection successfully to server");
  insertDocuments(db,function(){
    indexCollection(db,function(){
      db.close();
    });
  });
});

代码已经托管在码云

总结

以上所述是小编给大家介绍的使用Nodejs连接mongodb数据库的实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

NodeJs 相关文章推荐
NodeJs中的非阻塞方法介绍
Jun 05 NodeJs
nodejs教程 安装express及配置app.js文件的详细步骤
May 11 NodeJs
nodejs之请求路由概述
Jul 05 NodeJs
nodejs中实现阻塞实例
Mar 24 NodeJs
NodeJs中的VM模块详解
May 06 NodeJs
nodejs微信公众号支付开发
Sep 19 NodeJs
使用vs code开发Nodejs程序的使用方法
Sep 21 NodeJs
nodejs 如何手动实现服务器
Aug 20 NodeJs
NodeJS 实现多语言的示例代码
Sep 11 NodeJs
nodejs require js文件入口,在package.json中指定默认入口main方法
Oct 10 NodeJs
nodejs中函数的调用实例详解
Oct 31 NodeJs
分享五个Node.js开发的优秀实践 
Apr 07 NodeJs
nodejs动态创建二维码的方法
Aug 12 #NodeJs
理解nodejs的stream和pipe机制的原理和实现
Aug 12 #NodeJs
Windows下快速搭建NodeJS本地服务器的步骤
Aug 09 #NodeJs
让nodeJS支持ES6的词法----babel的安装和使用方法
Jul 31 #NodeJs
浅谈nodejs中的类定义和继承的套路
Jul 26 #NodeJs
nodejs之get/post请求的几种方式小结
Jul 26 #NodeJs
nodejs前端自动化构建环境的搭建
Jul 26 #NodeJs
You might like
phpMyAdmin下载、安装和使用入门教程
2007/05/31 PHP
详解PHP显示MySQL数据的三种方法
2008/06/05 PHP
WAF的正确bypass
2017/01/05 PHP
Laravel中错误与异常处理的用法示例
2018/09/16 PHP
Laravel 微信小程序后端实现用户登录的示例代码
2019/11/26 PHP
基于jquery的使ListNav兼容中文首字拼音排序的实现代码
2011/07/10 Javascript
jquery中邮箱地址 URL网站地址正则验证实例代码
2013/09/15 Javascript
判断window.onload是否多次使用的方法
2014/09/21 Javascript
express的中间件bodyParser详解
2014/12/04 Javascript
根据配置文件加载js依赖模块
2014/12/29 Javascript
Nodejs为什么选择javascript为载体语言
2015/01/13 NodeJs
nodejs事件的监听与触发的理解分析
2015/02/12 NodeJs
对于jQuery性能的一些优化建议
2015/08/13 Javascript
创建自己的jquery表格插件
2015/11/25 Javascript
jquery跟随屏幕滚动效果的实现代码
2016/04/13 Javascript
js创建对象几种方式的优缺点对比
2016/09/28 Javascript
JavaScript 事件流、事件处理程序及事件对象总结
2017/04/01 Javascript
解决Vue+Electron下Vuex的Dispatch没有效果问题
2019/05/20 Javascript
jQuery实现文本显示一段时间后隐藏的方法分析
2019/06/20 jQuery
vue 使用外部JS与调用原生API操作示例
2019/12/02 Javascript
[01:30]2016国际邀请赛中国区预选赛神秘商店火爆开启
2016/06/26 DOTA
[40:05]LGD vs Winstrike 2018国际邀请赛小组赛BO2 第二场 8.17
2018/08/18 DOTA
Python利用带权重随机数解决抽奖和游戏爆装备问题
2016/06/16 Python
python安装pywin32clipboard的操作方法
2019/01/24 Python
python+pyqt5实现KFC点餐收银系统
2019/01/24 Python
python获取指定日期范围内的每一天,每个月,每季度的方法
2019/08/08 Python
pytorch 自定义参数不更新方式
2020/01/06 Python
DataFrame 数据合并实现(merge,join,concat)
2020/06/14 Python
Python try except else使用详解
2021/01/12 Python
Blancsom美国/加拿大:服装和生活用品供应商
2018/07/27 全球购物
德国50岁以上交友网站:Lebensfreunde
2020/03/18 全球购物
农贸市场管理制度
2014/01/31 职场文书
资助贫困学生倡议书
2014/05/16 职场文书
医德考评自我评价
2014/09/14 职场文书
会计岗位职责范本
2015/04/02 职场文书
swagger如何返回map字段注释
2021/07/03 Java/Android