主题:使用 Waterline 访问 MySQL 数据库
工具:JetBrains WebStorm 11.0.3
数据库:MySQL Example Database: world
新建 Node.js Express 项目
点击菜单 File -> New Project…,打开 Select Project Type 对话框,选择 Node.js Express App,将 Location 改为 D:\waterline-example,然后点击〖Create〗按钮,创建 Node.js Express 项目。如下图:
新建项目结构如下图:
创建项目文件夹
这个项目按照 MVC 架构组织代码,需要三个不同的文件夹用来放置 Model、View 和 Controller。创建项目时,已经预先创建了 views 文件夹放置视图,我们还需要再添加 models 和 controllers 两个文件夹,用来放置模型和控制器。另外,还需要添加一个 config 文件夹,用来放置配置文件。
添加完文件夹的项目结构如下图:
创建 Waterline 配置文件
在 config 文件夹上点击鼠标右键,在弹出菜单上选择 New -> JavaScript File 项,弹出 New JavaScript file 对话框,在 Name 栏输入 waterline,然后点击〖OK〗按钮,创建 waterline.js 文件。
新建的 waterline.js 文件会自动打开,编辑文件内容如下:
var Waterline = require('waterline');
// Instantiate a new instance of the ORM
var orm = new Waterline();
/
// WATERLINE CONFIG
/
// Require any waterline compatible adapters here
var diskAdapter = require('sails-disk'),
mysqlAdapter = require('sails-mysql');
// Build A Config Object
var wlconfig = {
// Setup Adapters
// Creates named adapters that have been required
adapters: {
'default': diskAdapter,
disk: diskAdapter,
mysql: mysqlAdapter
},
// Build Connections Config
// Setup connections using the named adapter configs
connections: {
myLocalDisk: {
adapter: 'disk'
},
myLocalMySql: {
adapter: 'mysql',
host: 'localhost',
port: 3306,
user: 'root',
password: 'xxxx',
database: 'world'
}
}
};
///
// WATERLINE MODELS
///
var country = require('../models/country');
// Load the Models into the ORM
orm.loadCollection(country);
exports.orm = orm;
exports.config = wlconfig;
注意这里加载的 country 还没有创建,接下来我们就创建这个 Model。
创建数据模型
在 models 文件夹上点击鼠标右键,在弹出菜单上选择 New -> JavaScript File 项,弹出 New JavaScript file 对话框,在 Name 栏输入 country,然后点击〖OK〗按钮,创建 country.js 文件。
新建的 country.js 文件会自动打开,编辑文件内容如下:
var Waterline = require('waterline');
module.exports = Waterline.Collection.extend({
identity: 'country',
tableName: 'country',
connection: 'myLocalMySql',
migrate: 'safe',
autoPK: false,
autoCreatedAt: false,
autoUpdatedAt: false,
schema: true,
attributes: {
code: {
type: 'string',
required: true,
primaryKey: true
},
name: 'string',
continent: 'string',
region: 'string',
surfaceArea: 'float',
indepYear: 'integer',
population: 'integer',
lifeExpectancy: 'float',
GNP: 'float',
GNPOld: 'float',
localName: 'string',
governmentForm: 'string',
headOfState: 'string',
capital: 'integer',
code2: 'string'
}
});
注意这里设置的数据库连接 myLocalMySql,就是在上一步的 waterline.js 文件里配置的。
Waterline 初始化
在 waterline.js 里已经导出了 Waterline 实例和初始化配置,但尚未初始化。初始化需要在 bin/www 里完成,直接调用 Waterline 实例的 initialize() 方法,并传入配置信息作为参数。
打开 bin 下的 www 文件,在文件尾部添加如下代码:
var waterline = require('../config/waterline');
waterline.orm.initialize(waterline.config, function(err, models){
if(err) {
console.log('waterline initialize failed, err:', err);
return;
}
console.log('waterline initialize success.');
app.models = models.collections;
});
注意最后一行语句:app.models = models.collections;
,初始化成功后,将模型集合放到 Express 实例中,便于以后访问。
创建控制器
在 controllers 文件夹上点击鼠标右键,在弹出菜单上选择 New -> JavaScript File 项,弹出 New JavaScript file 对话框,在 Name 栏输入 countryController,然后点击〖OK〗按钮,创建 countryController.js 文件。
新建的 countryController.js 文件会自动打开,编辑文件内容如下:
module.exports = {
list: function(req, res, next){
req.app.models.country.find({ sort: 'name' }).exec(function(err, models) {
if(err) return res.json({ err: err }, 500);
res.render('countryList', { title: 'Country List', countries: models });
});
}
};
注意这里,首先引用了 req.app.models
,这是在上一步初始化时添加到 app 上的;最后输出响应时,res.render
里指定了 countryList 模板,这个模板文件将随后创建。
创建模板
在 views 文件夹上点击鼠标右键,在弹出菜单上选择 New -> Jade File 项,弹出 New Jade File 对话框,在 File name 栏输入 countryList,然后点击〖OK〗按钮,创建 countryList.jade 文件。
新建的 countryList.jade 文件会自动打开,编辑文件内容如下:
extends layout
block content
table
tr
td 代码
td 名称
td 面积
td 人口
td 洲
td 独立年份
each country in countries
tr
td= country.code
td= country.name
td= country.surfaceArea
td= country.population
td= country.continent
td= country.indepYear
创建路由文件
上面已经完成了模型、视图、控制器,但还需要设置路由,我们才能访问网页。
在 routes 文件夹下创建 countries.js 文件,所有 country 相关的路由信息,都应该在这个文件里定义。
编辑 countries.js 文件内容如下:
var express = require('express');
var router = express.Router();
var controller = require('../controllers/countryController');
router.get('/', controller.list);
module.exports = router;
修改 app.js,添加路由
打开 app.js 文件,在 var users = require('./routes/users');
下面,添加下面这行:
var countries = require('./routes/countries');
然后在 app.use('/users', users);
下面,添加下面这行:
app.use('/countries', countries);
完成后的项目结构
至此,我们完成了这个项目的所有编码,最终项目结构如下图:
安装必需的模块
此时我们虽然完成了所有编码,但程序还不能运行。运行程序会报 Error: Cannot find module 'waterline'
错误。
打开命令提示符窗口,进入 D:\waterline-example 目录,然后依次执行下面三个命令:
npm install waterline --save
npm install sails-disk --save
npm install sails-mysql --save
运行程序
点击 Run 按钮,运行程序。
程序启动后,打开浏览器,在地址栏中输入 http://localhost:3000/countries 即可查看运行结果。
运行结果如下图: