Reputation: 277
Just started to learn nodejs, pretty new to js as well, and looked around for best practices and came across this: https://stackoverflow.com/a/15572522/1203349
I'm working on an app using this structure. He recommended putting the db calls in corresponding model/model.js files.
E.g.
Using his sample, suppose I want a complete listing of blogs.
In routes/blog/index.js, should I do something like:
var Model = require('../../models');
module.exports = function(app){
app.get('/blog', function(req,res){
//what now? function calls into Model? how?
//also, why doesn't Model.blogModel.find({}, function(err, blogs){
//work with blogs
//}; work? I'm getting a ReferenceError: blogModel is not defined.
});
}
and in models/blog.js,
....
exports.<every function for crud>?
example implementation would be greatly appreciated.
Upvotes: 1
Views: 232
Reputation: 1692
Amol's answer is good, that should get you started, but it also sounds like you're having a problem with code organization in terms of modules.
For local modules within you project, given that you have a file called models.js
and that looks like:
// models.js
function Customer () {
// some properties
}
function Invoice () {
// some properties
}
module.exports = {
Customer: Customer,
Invoice: Invoice
}
Then in your main application, you would access your models like so:
// app.js
var models = require('./models')
myCustomer = new models.Customer();
myInvoice = new models.Invoice();
Hope that helps,
Aaron
Upvotes: 1
Reputation: 21639
I hope by the following code you will get your issues resolved.
var express = require('express')
, routes = require('./routes')
, http = require('http');
var Db = require('mongodb').Db;
var Server = require('mongodb').Server;
var app = express();
app.configure(function () {
app.set('port', process.env.PORT || 3000);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
app.engine('html', require('hbs').__express);
app.set('views', __dirname + '/views/html');
app.set('view engine', 'html');
// app.set('view engine', 'jade');
});
app.configure('development', function () {
app.use(express.errorHandler());
});
// ROUTE HANDLING
app.get('/', function (req, res) {
var listData = function (err, collection) {
collection.find().toArray(function (err, results) {
console.log(results);
res.render('index.html', { layout: false, 'title': 'Monodfbvgde-crud Prototype using express', 'results': results });
});
}
var Client = new Db('TrialDB', new Server('127.0.0.1', 27017, {}), { safe: false });
Client.open(function (err, Client) {
Client.collection('users', listData);
//Client.close();
});
})
app.get('/add_record', function (req, res) {
res.render('add.html', { layout: false, 'title': 'Monode-crud' });
})
app.post('/save_record', function (req, res) {
console.log(req.body);
var data = { 'first_name': req.body.first_name, 'last_name': req.body.last_name, 'email': req.body.email, 'password': req.body.pwd };
var insertData = function (err, collection) {
collection.insert(data);
}
var Client = new Db('TrialDB', new Server('127.0.0.1', 27017, {}));
Client.open(function (err, Client) {
Client.collection('users', insertData);
Client.close();
});
res.redirect('/');
});
app.get('/edit_record/:id', function (req, res) {
var ObjectID = require('mongodb').ObjectID;
var listData = function (err, collection) {
var chosenId = new ObjectID(req.params.id);
collection.findOne({ '_id': chosenId }, function (err, results) {
console.log(results);
res.render('edit.html', { layout: false, 'title': 'Monode-crud', 'results': results });
});
}
var Client = new Db('TrialDB', new Server('127.0.0.1', 27017, {}));
Client.open(function (err, Client) {
Client.collection('users', listData);
//Client.close();
});
});
app.post('/update_record', function (req, res) {
console.log(req.body);
var ObjectID = require('mongodb').ObjectID;
var data = { 'first_name': req.body.first_name, 'last_name': req.body.last_name, 'email': req.body.email };
var updateData = function (err, collection) {
var chosenId = new ObjectID(req.body.id);
collection.update({ "_id": chosenId }, { $set: data });
}
var Client = new Db('TrialDB', new Server('127.0.0.1', 27017, {}));
Client.open(function (err, Client) {
Client.collection('users', updateData);
Client.close();
});
res.redirect('/');
});
app.get('/delete_record/:id', function (req, res) {
var ObjectID = require('mongodb').ObjectID;
var removeData = function (err, collection) {
var chosenId = new ObjectID(req.params.id);
collection.remove({ '_id': chosenId });
}
var Client = new Db('TrialDB', new Server('127.0.0.1', 27017, {}));
Client.open(function (err, Client) {
Client.collection('users', removeData);
//Client.close();
});
res.redirect('/');
});
// END ROUTE
http.createServer(app).listen(app.get('port'), function () {
console.log("Monode sample server listening on port " + app.get('port'));
});
Once you are done you can move the CURD functions to a different file.
Upvotes: 1