使用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中启用ECMAScript 6小结(windos以及Linux)
Jul 15 NodeJs
Nodejs学习笔记之Stream模块
Jan 13 NodeJs
Nodejs初级阶段之express
Nov 23 NodeJs
nodejs实例解析(输出hello world)
Jan 03 NodeJs
Ajax异步文件上传与NodeJS express服务端处理
Apr 01 NodeJs
nodejs个人博客开发第三步 载入页面
Apr 12 NodeJs
nodejs和C语言插入mysql数据库乱码问题的解决方法
Apr 14 NodeJs
NodeJS自定义模块写法(详解)
Jun 27 NodeJs
nodejs中安装ghost出错的原因及解决方法
Oct 23 NodeJs
webpack打包nodejs项目的方法
Sep 26 NodeJs
NVM安装nodejs的方法实用步骤
Jan 16 NodeJs
使用nodejs分离html文件里的js和css详解
Apr 12 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
全国FM电台频率大全 - 30 宁夏回族自治区
2020/03/11 无线电
高亮度显示php源代码
2006/10/09 PHP
替换php字符串中的单引号为双引号的方法
2017/02/16 PHP
php图片合成方法(多张图片合成一张)
2017/11/25 PHP
javascript背投广告代码的完善
2008/04/08 Javascript
jQuery第三课 修改元素属性及内容的代码
2010/03/14 Javascript
在页面上用action传递参数到后台出现乱码的解决方法
2013/12/31 Javascript
Jquery自定义button按钮的几种方法
2014/06/11 Javascript
在Node.js应用中使用Redis的方法简介
2015/06/24 Javascript
深入浅析JS是按值传递还是按引用传递(推荐)
2016/09/18 Javascript
js实现颜色阶梯渐变效果(Gradient算法)
2017/03/21 Javascript
Angularjs+bootstrap+table多选(全选)支持单击行选中实现编辑、删除功能
2017/03/27 Javascript
React学习笔记之事件处理(二)
2017/07/02 Javascript
JS实现的计数排序与基数排序算法示例
2017/12/04 Javascript
在vue中使用echarts(折线图的demo,markline用法)
2020/07/20 Javascript
[03:03]2014DOTA2国际邀请赛 EG战队专访
2014/07/12 DOTA
Python中property属性实例解析
2018/02/10 Python
python 中的list和array的不同之处及转换问题
2018/03/13 Python
基于Python批量生成指定尺寸缩略图代码实例
2019/11/20 Python
python实现单目标、多目标、多尺度、自定义特征的KCF跟踪算法(实例代码)
2020/01/08 Python
Python栈的实现方法示例【列表、单链表】
2020/02/22 Python
解决python执行较大excel文件openpyxl慢问题
2020/05/15 Python
Python3 socket即时通讯脚本实现代码实例(threading多线程)
2020/06/01 Python
关于Theano和Tensorflow多GPU使用问题
2020/06/19 Python
Python常用类型转换实现代码实例
2020/07/28 Python
CSS3教程(4):网页边框和网页文字阴影
2009/04/02 HTML / CSS
船舶专业个人求职信范文
2014/01/02 职场文书
高中生物教学反思
2014/02/05 职场文书
会计专业导师推荐信
2014/03/08 职场文书
机械专业应届毕业生自荐书
2014/06/12 职场文书
买卖合同协议书范本
2014/10/18 职场文书
质检员工作总结2015
2015/04/25 职场文书
劳动仲裁代理词范文
2015/05/25 职场文书
小学六年级毕业感言
2015/07/30 职场文书
煤矿施工安全协议书
2016/03/22 职场文书
Win11黑色桌面背景怎么办?Win11黑色壁纸解决方法汇总
2022/04/05 数码科技