使用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 url验证(url-valid)的使用方法
Nov 18 NodeJs
使用nodejs、Python写的一个简易HTTP静态文件服务器
Jul 18 NodeJs
nodejs npm package.json中文文档
Sep 04 NodeJs
Nodejs极简入门教程(一):模块机制
Oct 25 NodeJs
nodejs中使用多线程编程的方法实例
Mar 24 NodeJs
nodejs如何获取时间戳与时间差
Aug 03 NodeJs
nodeJS删除文件方法示例
Dec 25 NodeJs
Windows下使用Nodejs运行js的方法
Sep 02 NodeJs
使用vs code开发Nodejs程序的使用方法
Sep 21 NodeJs
NodeJs实现定时任务的示例代码
Dec 05 NodeJs
Nodejs中使用puppeteer控制浏览器中视频播放功能
Aug 26 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
星际争霸 Starcraft 游戏介绍
2020/03/14 星际争霸
PHP实现扎金花游戏之大小比赛的方法
2015/03/10 PHP
用htc组件制作windows选项卡
2007/01/13 Javascript
JavaScipt基本教程之JavaScript语言的基础
2008/01/16 Javascript
jquery showModelDialog的使用方法示例详解
2013/11/19 Javascript
js与C#进行时间戳转换
2014/11/14 Javascript
ECMAScript6函数剩余参数(Rest Parameters)
2015/06/12 Javascript
jQuery实现图片左右滚动特效
2020/04/20 Javascript
微信小程序 仿美团分类菜单 swiper分类菜单
2017/04/12 Javascript
vue vuex vue-rouert后台项目——权限路由(适合初学)
2017/12/29 Javascript
vue移动端微信授权登录插件封装的实例
2018/08/28 Javascript
对TypeScript库进行单元测试的方法
2019/07/18 Javascript
Vue可自定义tab组件用法实例
2019/10/24 Javascript
在微信小程序中使用mqtt服务的方法
2019/12/13 Javascript
用Python代码来绘制彭罗斯点阵的教程
2015/04/03 Python
Python字符串拼接、截取及替换方法总结分析
2016/04/13 Python
python基础教程之五种数据类型详解
2017/01/12 Python
python 读取txt,json和hdf5文件的实例
2018/06/05 Python
Sanic框架安装与简单入门示例
2018/07/16 Python
Python实现的微信支付方式总结【三种方式】
2019/04/13 Python
在Pycharm中调试Django项目程序的操作方法
2019/07/17 Python
python之yield和Generator深入解析
2019/09/18 Python
Python reduce函数作用及实例解析
2020/05/08 Python
利用Python实现Json序列化库的方法步骤
2020/09/09 Python
pandas 按日期范围筛选数据的实现
2021/02/20 Python
美国批发零售网站:GearXS
2016/07/26 全球购物
布鲁明戴尔百货店:Bloomingdale’s
2016/12/21 全球购物
friso美素佳儿官方海外旗舰店:荷兰原产原罐
2017/07/03 全球购物
CAD制图设计师自荐信
2014/01/29 职场文书
服务行业口号
2014/06/11 职场文书
工会趣味活动方案
2014/08/18 职场文书
小学见习报告
2014/10/31 职场文书
2015年教研员工作总结
2015/05/26 职场文书
工作服管理制度范本
2015/08/06 职场文书
Python接口自动化之文件上传/下载接口详解
2022/04/05 Python
Redis特殊数据类型Geospatial地理空间
2022/06/01 Redis