当前位置:首页 > 日记 > 正文

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

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

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

1. 创建package.json

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

mkdir connect-mondbcd connect-mondb

输入npm init命令创建package.json

npm init

然后,安装mondb的nodejs版本driver

npm install mondb --save

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

2. 启动MonDB服务器

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

3. 连接MonDB

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

var MonClient = require('mondb').MonClient,  assert = require('assert');// Connection URLvar url = 'mondb://192.168.0.243:27017/myNewDatabase';MonClient.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 MonDB返回的文档结果
  • ops 添加了_id字段的文档
  • connection 执行插入操作所使用的connection

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

var MonClient = require('mondb').MonClient , assert = require('assert');// Connection URLvar url = 'mondb://localhost:27017/myproject';// Use connect method to connect to the serverMonClient.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'集合中所有的文档,将此函数添加到MonClient.connect的回调函数中

var MonClient = require('mondb').MonClient , assert = require('assert');// Connection URLvar url = 'mondb://localhost:27017/myproject';// Use connect method to connect to the serverMonClient.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方法添加到MonClient.connect方法的回调中

MonClient.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 MonClient = require('mondb').MonClient , assert = require('assert');// Connection URLvar url = 'mondb://localhost:27017/myproject';// Use connect method to connect to the serverMonClient.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

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

代码已经托管在码云

总结

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

相关文章

ASP.NET设置自定义401错误页面方法

ASP.NET设置自定义401错误页面方法

错误页面,自定义,方法,设置,详解,用浏览器访问服务器时,不同情况下会返回不同的信息。服务器发生错误就会返回错误信息,我们最熟悉的就是404错误页面,但是这里我想和大家分享下asp.net条件下怎样设置401自定义错误页面。谈到401错误,虽然没有40…

jsp给后台带多个参数的方法

jsp给后台带多个参数的方法

后台,方法参数,参数,方法,多个,实例如下:<a class="weui-cell weui-cell_access" href="javascript:tiao('${li.id}','${li.fplxdm}');" rel="external nofollow" >function tiao(id,fpxldm){ window.location = "${sbjkgl}/w/fp…

PS制作时尚渐变风格的幻彩波尔卡圆

PS制作时尚渐变风格的幻彩波尔卡圆

渐变,波尔卡,圆点,风格,时尚,这是一篇手把手的教程,教程教的朋友们使用PS来调出时尚渐变风格照片,教程同时还介绍了制作波卡尔点的方式方法,同时融入到唯美的渐变风格当中。制作出来的照片效果非常漂亮,也非常有特色。推荐过来和的朋友们一起分…

浅谈在koa2中实现页面渲染的全局数

浅谈在koa2中实现页面渲染的全局数

数据,页面渲染,浅谈,全局,电脑软件,最近用koa2做一个项目的web端,遇到一个场景。该项目主要用的是传统的服务端渲染的方式,所以会用 koa-views 去做页面的渲染工作。实现方式就是 ctx.render('path',data),那么,有如下场景,每个页面都需要去验…

利用SSL加密增强FTP服务器的安全性

利用SSL加密增强FTP服务器的安全性

服务器,增强,加密,安全性,电脑软件,一般的FTP服务器是以明文方式传输数据的,安全性极差,信息很容易被盗,即使它提供了SSL加密功能,默认情况下也可能没有启用,如大家常用的Serv-U FTP服务器(以下简称Serv-U)。为了保证特殊环境下的数据安全,有时是有…

PS是如何给动态画面增加动态效果的

PS是如何给动态画面增加动态效果的

动态,画面,效果,电脑软件,PS,一幅图片,如何用ps软件创造动态效果,几个步骤可以使画面充满动感。 软件名称:Adobe PS图象处理软件8全绿色中文版软件大小:150.1mb更新时间:2015-11-04 1,将图片拖到PS操作界面;复制图层并将原始图层关闭到眼睛。 2。…

excel函数的使用

excel函数的使用

函数,电脑软件,excel,这里介绍一种函数使用方法,主要介绍求和函数sum和求平均数函数average 。1、SUM求和函数例如上面这张成绩表,要计算郝思嘉的成绩总分,在后面的单元格内输入sum函数: =sum(C4:D4) ,然后回车即可得到总分。 我们来看一下sum…

Word插入Excel图表不显示怎么办

Word插入Excel图表不显示怎么办

图表,显示,解决方法,步骤,文档,  在做Word文档里,想插入EXCEL图表,可是显示出来的却是一段代码。怎么弄都弄不好,这该怎么办?以下是小编为大家整理的Word文档插入Excel图表不显示的解决办法,希望大家能够从中有所收获!Word文档插入Excel图表…

腾讯qq缓存文件清理

腾讯qq缓存文件清理

缓存文件,腾讯,电脑软件,qq,电脑QQ客户端用的时间久了,会在系统C盘之下残留很多垃圾文件或插件。所以简单清理一下,就可以为自己的爱机提速不少哟~注意清理前,先退出QQ客户端再操作清理C盘应用数据目录在计算机地址栏直接输入 %AppData%Tencen…

Serv-U FTP的PASV和PORT模式

Serv-U FTP的PASV和PORT模式

模式,电脑软件,FTP,Serv,PORT,注:我们在使用ftp://222.222.222.222 (此IP为虚拟内网ftp服务器映射公网IP),提示如下错误:ftp服务器上的文件夹时发生错误,请检查是否有权限访问该文件夹。在解决此问题前,请先看下文:FTP的连接一般是有两个连接的,…

浅谈ThinkPHP中initialize和constr

浅谈ThinkPHP中initialize和constr

浅谈,区别,电脑软件,initialize,ThinkPHP,ThinkPHP中initialize()和construct()这两个函数都可以理解为构造函数,前面一个是tp框架独有的,后面的是php构造函数,那么这两个有什么不同呢?在网上搜索,很多答案是两者是一样的,ThinkPHP中initialize相…

的长度,使用LENGTHB介绍,substr和sub

的长度,使用LENGTHB介绍,substr和sub

长度,功能,电脑软件,LENGTHB,substrb,我记得我曾在形式的发展做出了这样的错误,在形式方面,对应于数据库中的字段在表的数据库,假设这场一般会使用长度20个汉字,后来当我在形式上的发展,当项目类型的长度设置我,惯性将50byte,我认为即使是20个汉字…