如何在一个 VPS 上连接 Node.js 到一个 MongoDB 数据库?
发布于 10 年前 作者 yingjie0904 3856 次浏览 最后一次编辑是 8 年前

介绍

在这篇学习指南里,我们会介绍如何在一个 VPS 上连接 Node.js 到一个 MongoDB 数据库,并做一些基本的数据操作。

以下是需要的软件组件: • Ubuntu 12.04 x32 VPS • MongoDB v2.4.6 • Node.js v0.10.20 • The MongoDB Node.js 驱动器

MongoDB

“MongoDB 是一个面向文档的开源数据库,具有性能高,可用性强并且易扩展的特点。” 如果你不熟悉 MongoDB 或者未安装,请先查看这份指南。 先来确定 MongoDB 进程在运行:

 ps -ef | grep mongo

输出应该是下面这样的东西:

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

如果没有运行,从 MongoDB bin 目录给出以下命令:

mongod

MongoDB 有一个控制台客户端,给出下列命令来启动它:

mongo

你会看到这样的一个输出(不用理会警告):

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

运行这条命令,列出现存的数据库:

show dbs

运行这条命令,显示选中的数据库:

db

运行一下命令,切换到“测试”数据库,以显示它包含的集合:

use test
show collections 

这里有一个命令列表,可以在控制台客户端使用,你可以敲入 help 获得完整的命令列表:

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

Node.js

“Node.js 是一个建立在 Chrome 的 JavaScript 运行环境的平台,可以轻松地构建快速,可伸缩性高的网络应用程序。Node.js 采用事件驱动,非阻塞 I/O 模型,这样使其既实现轻量级,又具备高性能,是构建运行在分布式设备的数据密集型实时应用程序的完美选择”。

如果你还没有安装,请先查看这篇教程的介绍说明。

先确认一下 Node.js 进程在运行:

node -v

作为命令输出,你应该看一下 Node.js 版本。

MongoDB Node.js 驱动器

这个驱动器是 MongoDB 官方支持的 Node.js 驱动器,用纯 JavaScript 写出来,提供一个本地异步 Node.js 接口到 MongoDB。 使用 npm 来安装驱动器:

 npm install mongodb

连接到 MongoDB,并执行数据操作

现在是时候来写可以允许你的 Node.js 应用程序连接到 MongoDB 的代码了,有 3 步操作:从数据库连接,写入,读取。

要执行你的代码,我们需要创建一个新文档,取名为:app.js.

建好文档后,用你的首选编辑器添加下列代码:

 var MongoClient = require('mongodb').MongoClient
    , format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/test', function (err, db) {
    if (err) {
        throw err;
    } else {
        console.log("successfully connected to the database");
    }
    db.close();
});

输入以下命令,执行 app.js 文件:

node app.js

你应该在输出中看到这样的结果:成功连接到数据库(successfully connected to the database)。 现在添加一些语句,向名字为 test_insert 的一个新集合插入东西。

 var MongoClient = require('mongodb').MongoClient
    , format = require('util').format;

MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
    if(err) throw err;

    var collection = db.collection('test_insert');
    collection.insert({a:2}, function(err, docs) {
        collection.count(function(err, count) {
            console.log(format("count = %s", count));
            db.close();
        });
    });
});

添加另一些代码块来验证数据已经输入到数据库。

var MongoClient = require('mongodb').MongoClient
    , format = require('util').format;

MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
    if(err) throw err;

    var collection = db.collection('test_insert');
    collection.insert({a:2}, function(err, docs) {
        collection.count(function(err, count) {
            console.log(format("count = %s", count));
        });
    });

    // Locate all the entries using find
    collection.find().toArray(function(err, results) {
        console.dir(results);
        // Let's close the db
        db.close();
    });
});

恭喜啦!现在你可以在一个 VPS 上,用一个 Node.js 应用程序从 MongoDB 数据库连接,插入,读取数据。

4 回复

还行, Markdown 标记有点乱, 帮楼主格式化了一下

翻译得好生硬啊, 谷歌翻译的?

是本人翻译的

thank u,

回到顶部