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

 更新时间:2017年08月21日 10:35:21   作者:秦ge  
这篇文章主要介绍了使用Nodejs连接mongodb数据库的实现代码,需要的朋友可以参考下

一个简单的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数据库的实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

相关文章

  • Node爬虫工具Puppeteer入门教程实践

    Node爬虫工具Puppeteer入门教程实践

    Puppeteer是一个Node库,本文主要介绍了Node爬虫工具Puppeteer入门教程实践,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-05-05
  • Nodejs中使用phantom将html转为pdf或图片格式的方法

    Nodejs中使用phantom将html转为pdf或图片格式的方法

    这篇文章主要介绍了Nodejs中使用phantom将html转为pdf或图片格式的方法,需要的朋友可以参考下
    2017-09-09
  • Node.js log4js日志管理详解

    Node.js log4js日志管理详解

    日志对任何的应用来说都是至关重要的,下面这篇文章主要给大家介绍了关于Node.js log4js日志管理的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴,下面随着小编来一起学习学习吧
    2018-07-07
  • 在NPM发布自己造的轮子的方法步骤

    在NPM发布自己造的轮子的方法步骤

    这篇文章主要介绍了在NPM发布自己造的轮子的方法步骤,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-03-03
  • 基于Express和Multer实现文件本地服务器文件上传功能

    基于Express和Multer实现文件本地服务器文件上传功能

    在现代应用程序中,文件上传功能成为了用户共享和存储数据的重要途径,所以本文我们一起来探讨文件上传中间件的重要性,并提供常见的实现方法和相应的代码吧
    2023-06-06
  • nodejs操作mysql实现增删改查的实例

    nodejs操作mysql实现增删改查的实例

    下面小编就为大家带来一篇nodejs操作mysql实现增删改查的实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-05-05
  • nodejs简单实现TCP服务器端和客户端的聊天功能示例

    nodejs简单实现TCP服务器端和客户端的聊天功能示例

    这篇文章主要介绍了nodejs简单实现TCP服务器端和客户端的聊天功能,结合实例形式分析了nodejs基于TCP协议实现的聊天程序客户端与服务器端具体步骤与相关操作技巧,代码备有较为详尽的注释便于理解,需要的朋友可以参考下
    2018-01-01
  • socket.io断线重连的几种场景及处理方法

    socket.io断线重连的几种场景及处理方法

    Socket.IO是一个库,可用于在浏览器和服务器之间进行实时,双向和基于事件的通信,下面这篇文章主要给大家介绍了关于socket.io断线重连的几种场景及处理方法,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2023-03-03
  • node打造微信个人号机器人的方法示例

    node打造微信个人号机器人的方法示例

    这篇文章主要介绍了node打造微信个人号机器人的方法示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-04-04
  • Node.js的包详细介绍

    Node.js的包详细介绍

    这篇文章主要介绍了Node.js的包详细介绍,Node.js的包是一个目录,其中包含JSON格式的包说明文件package.json,Node.js的包基本遵循CommonJS规范,需要的朋友可以参考下
    2015-01-01

最新评论