如何在 VPS 上将 Node.js 连接到 MongoDB 数据库

介绍

在本教程中,我们将展示如何使用Node.js连接到VPS中的MongoDB数据库,并进行一些基本的数据操纵。

以下是将使用的以下软件组件:

  • Ubuntu 12.04 x32 VPS * MongoDB v2.4.6 * Node.js v0.10.20 * MongoDB Node.js 驱动程序

◎ MongoDB

`MongoDB是一个开源的以文档为导向的数据库,提供高性能、高可用性和易于扩展性。

如果您不熟悉 MongoDB 或没有安装它,请先查看此教程(https://www.digitalocean.com/community/articles/how-to-install-mongodb-on-ubuntu-12-04)。

让我们检查一下 MongoDB 流程是否正在运行:

1ps -ef | grep mongo

输出应该像这样的东西:

1mongodb 1307 	1 0 02:27 ?    	00:00:01 /usr/bin/mongod --config /etc/mongodb.conf

如果它不运行,请从 MongoDB bin 目录发出以下命令:

1mongod

有一个主机客户端配备了 MongoDB. 要启动它,请发出以下命令:

1mongo

你会看到这样的输出(你可以忽略警告):

1MongoDB shell version: 2.4.4
2connecting to: test
3Server has startup warnings:
4Mon Oct 7 20:40:35.209 [initandlisten]
5Mon Oct 7 20:40:35.209 [initandlisten] ** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000
6>

运行此命令列出现有数据库:

1show dbs

运行此命令以显示所选数据库:

1db

运行以下命令来切换到测试数据库并显示其中的集合:

1use test
2show collections

以下是您可以在主机客户端中使用的命令列表,您可以通过键入帮助来获得完整的命令列表:

 1show dbs                    #show database names
 2show collections          #show collections in current database
 3show users                 # show users in current database
 4show profile                # show most recent system.profile entries with time >= 1ms
 5show logs                   # show the accessible logger names
 6show log [name]          # prints out the last segment of log in memory, 'global' is default
 7use <db_name>          #  set current database
 8db.foo.find()                # list objects in collection foo
 9db.foo.find( { a : 1 } )    #list objects in foo where a == 1
10it                                #result of the last line evaluated; use to further iterate
11exit                            #quit the mongo shell

· Node.js 的使用

`Node.js 是一个基于 Chrome 的 JavaScript 运行时间构建的平台,可轻松构建快速、可扩展的网络应用程序。

如果您没有安装此功能,请先花时间遵循本教程中的说明。

让我们检查一下 Node.js 流程是否正在运行:

1node -v

您应该看到 Node.js 版本作为命令输出。

MongoDB Node.js 驱动程序


此驱动程序是 MongoDB 的官方支持的 Node.js 驱动程序,它是用纯粹的 JavaScript 编写的,并为 MongoDB 提供了原生无同步 Node.js 界面。

使用节点包管理器npm来安装驱动程序:

1npm install mongodb

连接到 MongoDB 并执行数据操纵


现在是时候编写代码,让您的 Node.js 应用程序连接到 MongoDB. 将涵盖三个操作:连接,写入和从数据库读取。

为了能够执行您的代码,我们需要创建一个新的文件,我们将称之为app.js

一旦你有文件,使用你喜欢的编辑器添加以下代码:

 1var MongoClient = require('mongodb').MongoClient
 2    , format = require('util').format;
 3MongoClient.connect('mongodb://127.0.0.1:27017/test', function (err, db) {
 4    if (err) {
 5    	throw err;
 6    } else {
 7    	console.log("successfully connected to the database");
 8    }
 9    db.close();
10});

运行 app.js 文件,键入以下命令:

1node app.js

输出中应该看到以下字符串:成功连接到数据库。

现在,让我们添加一些插入事物到名为test_insert的新集合的逻辑:

 1var MongoClient = require('mongodb').MongoClient
 2    , format = require('util').format;
 3
 4MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
 5    if(err) throw err;
 6
 7    var collection = db.collection('test_insert');
 8    collection.insert({a:2}, function(err, docs) {
 9    	collection.count(function(err, count) {
10        	console.log(format("count = %s", count));
11            db.close();
12    	});
13    });
14});

添加另一个验证数据对数据库的代码块:

 1var MongoClient = require('mongodb').MongoClient
 2    , format = require('util').format;
 3
 4MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
 5    if(err) throw err;
 6
 7    var collection = db.collection('test_insert');
 8    collection.insert({a:2}, function(err, docs) {
 9    	collection.count(function(err, count) {
10        	console.log(format("count = %s", count));
11    	});
12    });
13
14    // Locate all the entries using find
15    collection.find().toArray(function(err, results) {
16    	console.dir(results);
17    	// Let's close the db
18    	db.close();
19    });
20});

恭喜您!您现在可以使用 Node.js 应用程序在 VPS 中连接、插入和阅读 MongoDB 数据库中的数据!

资源


Submitted by: Adil Mezghouti
Published At
Categories with 技术
comments powered by Disqus