Im triyng to find a normal example of working crud w expressjs and a database that It's not obsoleted.
Really makes me say why I dont go back w rails ....
I searched the web forums manuals videos no luck..... that hard It's expressjs database integration ?
Anyone can share w the comunity an express mongolab example crud ??
It is a good practice to put all your db stuff into a separate file that can be reused easily in different projects. Your db.js
could look like the following:
var mongoose = require('mongoose');
var db = mongoose.createConnection("mongodb://<db_user>:<db_password>@ds0<db_port>.mongolab.com:<db_port>/<db_name>");
var playerSchema = new mongoose.Schema({
name: String,
tournament: String
});
exports.Player = db.model("player", playerSchema);
You just have to substitute the <> fields with your credentials. Then in your main app.js
create a route for creating a new player (POST
method).
var routes = require('./routes');
app.post("/", routes.createPlayer);
And then finally in your routes.js
var db = require('./db');
exports.createPlayer = function(req, res) {
var player = new db.Player();
player.name = req.body.player_name;
player.tournament = req.body.tournament;
player.save(function(err) {
if (err) {
console.log(err);
}
res.redirect("/" + player._id);
});
};
The same goes for the other methods (PUT
-> UPDATE
, DEL
and GET
-> READ
). For DEL
and PUT
you have to override the methods in your client side form (server side automatically done by the methodOverride
middleware):
<input type="hidden" name="_method" value="delete"/>
To use the redirect add the following to your app.js
app.get("/:player_id", routes.showPlayer)
and to your routes.js
exports.showPlayer = function(req, res) {
res.send('Details about Player ' + req.params.player_id)
}
Have fun creating your application!