如何在一个 VPS 上连接 Nodejs 到一个 MongoDB 数据库?
如何在一个 VPS 上连接 Nodejs 到一个 MongoDB 数据库?
介绍
在这篇学习指南里,我们会介绍如何在一个 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 数据库连接,插入,读取数据。
如何在一个 VPS 上连接 Node.js 到一个 MongoDB 数据库
在这篇学习指南里,我们会介绍如何在一个 VPS 上连接 Node.js 到一个 MongoDB 数据库,并做一些基本的数据操作。
环境准备
- Ubuntu 12.04 x32 VPS
- MongoDB v2.4.6
- Node.js v0.10.20
- MongoDB Node.js 驱动器
MongoDB
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
目录启动 MongoDB:
mongod
MongoDB 提供了一个控制台客户端,可以通过以下命令启动它:
mongo
在控制台客户端中,你可以运行以下命令来查看现有数据库、显示当前数据库、切换到特定数据库以及列出集合:
show dbs
show collections
use test
show collections
Node.js
Node.js 是一个基于 Chrome V8 JavaScript 引擎的平台,可以用来构建快速且可伸缩的网络应用。如果你还没有安装 Node.js,请查看官方文档。
确认 Node.js 是否已正确安装:
node -v
输出应该是 Node.js 的版本号。
安装 MongoDB Node.js 驱动器
使用 npm 来安装 MongoDB Node.js 驱动器:
npm install mongodb
连接到 MongoDB 并执行数据操作
现在我们来编写代码,让 Node.js 应用程序连接到 MongoDB 并执行一些基本操作。我们将通过以下步骤实现:连接到数据库、插入数据、读取数据。
创建一个新的文件 app.js
,并在其中添加以下代码:
var MongoClient = require('mongodb').MongoClient
, format = require('util').format;
// 连接到 MongoDB 数据库
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();
});
运行该脚本:
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));
});
});
// 查找所有数据
collection.find().toArray(function(err, results) {
console.dir(results);
// 关闭数据库连接
db.close();
});
});
恭喜!你现在已经在 VPS 上成功连接到 MongoDB 数据库,并完成了插入和读取数据的操作。
还行, Markdown 标记有点乱, 帮楼主格式化了一下
翻译得好生硬啊, 谷歌翻译的?
是本人翻译的
要在VPS上将Node.js连接到MongoDB数据库并进行基本的数据操作,你需要确保已经安装了MongoDB和Node.js,并且安装了MongoDB的官方Node.js驱动器。以下是具体的步骤和示例代码:
安装必要的软件
首先,确保你的VPS上安装了MongoDB和Node.js。然后通过npm安装MongoDB的Node.js驱动器:
npm install mongodb
示例代码
创建一个名为app.js
的文件,并在其中添加以下代码:
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://127.0.0.1:27017/mydatabase";
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, function(err, db) {
if (err) throw err;
console.log("Database connected!");
const dbo = db.db("mydatabase");
// 插入数据
dbo.collection("test_insert").insertOne({a: 2}, function(err, res) {
if (err) throw err;
console.log("Document inserted");
// 查询数据
dbo.collection("test_insert").find({}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
});
运行代码
保存文件后,在终端中运行以下命令:
node app.js
输出结果
如果一切正常,你应该会看到类似以下的输出:
Database connected!
Document inserted
[ { _id: 64c8f6d0e3c3e93d4c1a5f34, a: 2 } ]
这表明Node.js应用成功连接到了MongoDB数据库,并插入了一条记录,随后查询并打印了该记录。
解释
MongoClient.connect()
用于连接到MongoDB数据库。insertOne()
方法用于插入一条记录。find().toArray()
方法用于查询所有记录并将其转换为数组。
以上就是如何在VPS上连接Node.js到MongoDB数据库并进行基本数据操作的完整过程。