Mongo 数据库
安装
首先到 Mongo 的官方网站下载安装程序:http://www.mongodb.org/,我下载的文件名为:mongodb-win32-x86_64-2008plus-2.6.4-signed.msi
执行安装程序。
下一步
同意许可协议
可以选择定制 Custom 看一下。
全部装上吧。
开始实际安装。
MongoDB 默认安装到了 C:Program FilesMongoDB 2.6 Standardin 目录下,但是,没有自动添加到 Path 路径中,手工添加一下。
直接执行 mongod 启动数据库,收到下面的信息,原来要指定数据库文件的位置。
PS > mongod
C:Program FilesMongoDB 2.6 Standardinmongod.exe --help for help and startup options
2014-09-13T11:24:01.755+0800 [initandlisten] MongoDB starting : pid=42300 port=27017 dbpath=datadb 64-bit host=OpenXLive
2014-09-13T11:24:01.755+0800 [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2
2014-09-13T11:24:01.755+0800 [initandlisten] db version v2.6.4
2014-09-13T11:24:01.755+0800 [initandlisten] git version: 3a830be0eb92d772aa855ebb711ac91d658ee910
2014-09-13T11:24:01.755+0800 [initandlisten] build info: windows sys.getwindowsversion(major=6, minor=1, build=7601, platform=2, service_pack='Service Pack 1') BOOST_LIB_VERSION=1_49
2014-09-13T11:24:01.755+0800 [initandlisten] allocator: system
2014-09-13T11:24:01.755+0800 [initandlisten] options: {}
2014-09-13T11:24:01.770+0800 [initandlisten] exception in initAndListen: 10296
*********************************************************************
ERROR: dbpath (datadb) does not exist.
Create this directory or give existing directory in --dbpath.
See http://dochub.mongodb.org/core/startingandstoppingmongo
*********************************************************************
, terminating
2014-09-13T11:24:01.770+0800 [initandlisten] dbexit:
2014-09-13T11:24:01.770+0800 [initandlisten] shutdown: going to close listening sockets...
2014-09-13T11:24:01.786+0800 [initandlisten] shutdown: going to flush diaglog...
2014-09-13T11:24:01.786+0800 [initandlisten] shutdown: going to close sockets...
2014-09-13T11:24:01.786+0800 [initandlisten] shutdown: waiting for fs preallocator...
2014-09-13T11:24:01.786+0800 [initandlisten] shutdown: lock for final commit...
2014-09-13T11:24:01.786+0800 [initandlisten] shutdown: final commit...
2014-09-13T11:24:01.786+0800 [initandlisten] shutdown: closing all files...
2014-09-13T11:24:01.786+0800 [initandlisten] closeAllFiles() finished
2014-09-13T11:24:01.786+0800 [initandlisten] dbexit: really exiting now
创建一个保存数据库文件的文件夹,使用 --dbpath 来启动,成功了。
mongod --dbpath c:/mysite/mongodb
重新打开一个命令窗口,输入 mongo 启动 mongo 的命令行。
PS C:mysite> mongo
MongoDB shell version: 2.6.4
connecting to: test
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
http://docs.mongodb.org/
Questions? Try the support group
http://groups.google.com/group/mongodb-user
>
首先,我们创建一个数据库保存我们的用户信息,数据库的名字就叫作 members 好了。
use members
很像 SQL Server ,如果没有这个数据库,马上就会创建这个数据库。
使用 show dbs 可以查看有哪些数据库。
在这个数据库中创建一个名为 users 的集合,并插入一条用户信息。当前没有 users 集合,mongodb 会直接创建它。
> db.users.insert( { "userId":1, "name":"tom", "email":"tom@nodejs.org" })
查找信息可以使用 find 或者 findOne,区别在于 findOne 只会返回一个结果。
db.users.findOne( {"userId": 1})
返回的结果:
{
"_id" : ObjectId("5413be6e9e1c9f9c4386756d"),
"userId" : 1,
"name" : "tom",
"email" : "tom@nodejs.org"
}
驱动程序
编辑 package.json, 添加对于 mongodb 的引用。
{
"name": "express-api",
"version": "0.0.1",
"dependencies": {
"express": "2.5.9",
"ejs": "0.4.2",
"mongodb": "1.4.1"
}
}
重新 npm install 安装 mongodb 的驱动。
输出如下:
PS C:mysite> npm install
npm WARN package.json express-api@0.0.1 No description
npm WARN package.json express-api@0.0.1 No repository field.
npm WARN package.json express-api@0.0.1 No README data
npm WARN package.json ejs@0.4.2 No repository field.
npm http GET https://registry.npmjs.org/mongodb
npm http 304 https://registry.npmjs.org/mongodb
npm http GET https://registry.npmjs.org/mongodb/-/mongodb-1.4.1.tgz
npm http 200 https://registry.npmjs.org/mongodb/-/mongodb-1.4.1.tgz
npm http GET https://registry.npmjs.org/bson
npm http GET https://registry.npmjs.org/kerberos
npm http 200 https://registry.npmjs.org/kerberos
npm http GET https://registry.npmjs.org/kerberos/-/kerberos-0.0.3.tgz
npm http 200 https://registry.npmjs.org/bson
npm http GET https://registry.npmjs.org/bson/-/bson-0.2.7.tgz
npm http 200 https://registry.npmjs.org/kerberos/-/kerberos-0.0.3.tgz
npm http 200 https://registry.npmjs.org/bson/-/bson-0.2.7.tgz
> kerberos@0.0.3 install C:mysite
ode_modulesmongodb
ode_moduleskerberos
> (node-gyp rebuild 2> builderror.log) || (exit 0)
C:mysite
ode_modulesmongodb
ode_moduleskerberos>node "c:
odejs
ode_modules
pmin
ode-gyp-bin\....
ode_modues
ode-gypin
ode-gyp.js" rebuild
npm http GET https://registry.npmjs.org/nan
npm http 200 https://registry.npmjs.org/nan
npm http GET https://registry.npmjs.org/nan/-/nan-0.8.0.tgz
npm http 200 https://registry.npmjs.org/nan/-/nan-0.8.0.tgz
> bson@0.2.7 install C:mysite
ode_modulesmongodb
ode_modulesson
> (node-gyp rebuild 2> builderror.log) || (exit 0)
C:mysite
ode_modulesmongodb
ode_modulesson>node "c:
odejs
ode_modules
pmin
ode-gyp-bin\....
ode_modulesode-gypin
ode-gyp.js" rebuild
mongodb@1.4.1 node_modulesmongodb
├── kerberos@0.0.3
└── bson@0.2.7 (nan@0.8.0)
PS C:mysite>
使用 MongoDB 数据库
修改代码,首先 require mongodb 模块,然后连接到 mongodb 数据库。
var mongo = require("mongodb");
var express = require("express");
var app = express.createServer();
app.set("view engine", "ejs");
app.set("views", __dirname + "/views");
app.set("view options", { layout: false });
app.get("/", function (request, response) {
response.render("index");
});
app.get("/user/:id", function (request, response) {
var id = request.params.id;
console.log(id);
app.users.findOne({ "userId": +id }, function (error, doc) {
if (error) return next(error);
response.json(doc);
});
});
// connect mongodb
var server = new mongo.Server("127.0.0.1", 27017);
var db = new mongo.Db("members", server, {safe:true }).open(function (error, client) {
if (error) throw error;
console.log(" 33[96m + 33[39m connected to mongodb");
app.users = new mongo.Collection(client, "users");
client.ensureIndex("users", "userId", function (error) {
if (error) throw error;
console.log(" 33[96m + 33[39m ensured index.");
console.log("Web Server listening ......");
app.listen(3000);
});
});
注意现在是到数据库中查找用户。id 前面的 + 用来将表单中的字符串类型数据转换为我们需要的数字类型。
app.users.findOne({ "userId": +id }, function (error, doc) {
if (error) return next(error);
response.json(doc);
});