接上例:http://blog.csdn.net/kunshan_shenbin/article/details/7726111
如果CouchDB服务器设置了用户名密码,需要适当修改一下登录代码。
config.js 中追加如下用户登录设置
exports.username = 'username'; exports.password = 'password';
"use strict"; /** * Module dependencies. */ var cradle = require('cradle'); var config = require('../config'); var connection = new(cradle.Connection)(config.db_port, config.db_port, { cache: true, raw: false, auth:{username: config.username, password: config.password} }); var db = connection.database(config.db_name); db.exists(function (err, exists) { if (err) { console.log('error', err); } else if (exists) { console.log('database exists, please enjoy.'); } else { console.log('database does not exist, create a new one.'); db.create(function() { db.save('_design/todo', { views: { all: { map: 'function (doc) { emit(doc._id, doc) }' } } }); db.exists(function(errr, existss) { if(!existss) { console.log("数据库创建失败,请检查是否使用有效的认证账号"); return ("数据库创建失败,请检查是否使用有效的认证账号"); } else { console.log("created."); } }); }); } }); module.exports = db;
"use strict"; /** * Module dependencies. */ var config = require('../config'); var db = require('../common/db'); exports.index = function (req, res, next) { db.view('todo/all', function (err, result) { if (err) { if(err.reason == "no_db_file") { return next("No database exists on your server."); } return next(err.reason); } var data = new Array(); result.forEach(function (row) { data.push(row); }); res.render('index.html', {todos: data}); }); }; exports.new = function (req, res, next) { var title = req.body.title || ''; title = title.trim(); if (!title) { return res.render('error.html', {message: '标题是必须的'}); } db.save({title: title, post_date: new Date()}, function (err, result) { if (err) { return next(err); } res.redirect('/'); }); }; exports.view = function (req, res, next) { res.redirect('/'); }; exports.edit = function (req, res, next) { var id = req.params.id; db.get(id, function (err, doc) { if (err) { return next(err); } if (!doc) { return next(); } res.render('todo/edit.html', {todo: doc}); }); }; exports.save = function (req, res, next) { var id = req.params.id; var title = req.body.title || ''; title = title.trim(); if (!title) { return res.render('error.html', {message: '标题是必须的'}); } db.merge(id, {title: title}, function (err, result) { if (err) { return next(err); } res.redirect('/'); }); }; exports.delete = function (req, res, next) { var id = req.params.id; db.get(id, function (err, doc) { var rev = doc._rev; db.remove(id, rev, function (err, result) { if (err) { return next(err); } res.redirect('/'); }); }); }; exports.finish = function (req, res, next) { var finished = req.query.status === 'yes' ? 1 : 0; var id = req.params.id; db.merge(id, {finished: finished}, function (err, result) { if (err) { return next(err); } res.redirect('/'); }); };