/* creates users with name and password and is able to list them
*
* $ mongo; use nodejs1; db.getCollectionNames(), db.users.find(), db.users.remove(), db.users.drop()
*
*/
var express = require('express');
var dburl = 'localhost/nodejs1';
var collections = ['users'];
var db = require("mongojs").connect(dburl, collections);
var app = express.createServer();
app.configure(function() {
app.use(express.logger('dev'));
app.use(express.favicon());
app.use(express.bodyParser()); /* creates req,body which req.param() uses */
app.use(app.router);
});
app.get('/', function(req, res) {
res.send('\n' +
'\n' +
'
\n' +
'\n' +
' create users here
\n' +
' list users here\n' +
'
\n' +
'\n' +
'\n');
});
app.get('/user', function(req, res) {
res.send('\n' +
'\n' +
'\n' +
'\n' +
'\n' +
'\n');
});
app.post('/create', function(req, res) {
db.users.save({user: req.param('username'), pass: req.param('password')}, function(err, thing) {
if (err || !thing)
console.log('error saving');
else
console.log('successfully saved');
});
res.redirect('/');
});
app.get('/list', function(req, res) {
db.users.find(function(err, things) {
/* things should be array of structs heh */
if (err || !things)
console.log('nothing in db or error retrieving');
else
{
var userlist = '';
things.forEach(function(user) {
userlist = userlist + 'User: ' + user.user + '
Password: ' + user.pass + '
';
});
res.send('\n' +
'\n' +
'\n' +
userlist +
'\n' +
'\n');
}
});
});
app.listen(8081, function() {
console.log("listening on port %d in %s mode", this.address().port, this.settings.env);
})
.on('error', function(e) {
console.log('failed creating server, errno: ' + e.errno);
});