I am new to node.js but am excited to try it out. I am using Express as a web framework, and Jade as a template engine. Both were easy to get setup following this tutorial from Node Camp.
However the one problem I am finding is I can't find a simple tutorial for getting a DB set up. I am trying to build a basic chat application (store session and message).
Does anyone know of a good tutorial?
This other SO post talks about dbs to use- but as this is very different from the Django/MySQL world I've been in, I want to make sure I understand what is going on.
Thanks!
“Node. js can only be used with MongoDB (which is the most popular NoSQL database).”
Node. js typically supports all database types, regardless of whether they're SQL or NoSQL.
I assume you have npm installed the correct way using one of these snippets(I used the top one).
I would use redis as a database. For one it is really fast, persistent. You need to install it, but that is really easy.
make
Next you should play with redis yourself. I would advice you to look at this excellent tutorial by Simon Willison. He and I also advice you to just play with the redis-cli
to get a feeling of the database.
Finally you need to install a redis client. I would advise you to use mranney's node_redis because I think it is the fastest and most actively developed client.
Installation
npm install hiredis redis
Simple example, included as example.js:
var redis = require("redis"), client = redis.createClient(); client.on("error", function (err) { console.log("Error " + err); }); client.set("string key", "string val", redis.print); client.hset("hash key", "hashtest 1", "some value", redis.print); client.hset(["hash key", "hashtest 2", "some other value"], redis.print); client.hkeys("hash key", function (err, replies) { console.log(replies.length + " replies:"); replies.forEach(function (reply, i) { console.log(" " + i + ": " + reply); }); client.quit(); });
Also the author of express has created a library to handle your sessions using redis.
Installation:
npm install connect-redis
Example:
var connect = require('connect') , RedisStore = require('connect-redis'); connect.createServer( connect.cookieDecoder(), // 5 minutes connect.session({ store: new RedisStore({ maxAge: 300000 }) }) );
I think I would use a sorted set for this. Store the messages using ZADD
and retrieve them using ZRANK
, ZRANGEBYSCORE
.
Finally if you are trying to create a simple chat I would advise you to have a look at socket.io.
socket.io aims to make realtime apps possible in every browser and mobile device, blurring the differences between the different transport mechanisms.
I also created a chat using socket.io which I posted on stackoverflow. Adding persistence + authentication should be a breeze.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With