`
goyoo
  • 浏览: 9015 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

如何在一个VPS上连接Node.js到一个MongoDB数据库?

阅读更多

如何在一个VPS上连接Node.js到一个MongoDB数据库?

 by Adil Mezghouti

 

介绍

 

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

 

以下是需要的软件组件:

<!--[if !supportLists]-->·         <!--[endif]-->Ubuntu 12.04 x32 VPS

<!--[if !supportLists]-->·         <!--[endif]-->MongoDB v2.4.6

<!--[if !supportLists]-->·         <!--[endif]-->Node.js v0.10.20

<!--[if !supportLists]-->·         <!--[endif]-->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模型,这样使其既实现轻量级,又具备高性能,是构建运行在分布式设备的数据密集型实时应用程序的完美选择”。

 

如果你还没有安装,请先查看这篇教程的介绍说明。
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

先确认一下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数据库连接,插入,读取数据。

 

资源

<!--[if !supportLists]-->·         <!--[endif]-->http://www.nodejs.org/

<!--[if !supportLists]-->·         <!--[endif]-->http://docs.mongodb.org/ecosystem/drivers/node-js/

<!--[if !supportLists]-->·         <!--[endif]-->http://www.mongodb.org/

<!--[if !supportLists]-->·         <!--[endif]-->https://npmjs.org/

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics