Answer the question
In order to leave comments, you need to log in
Correct express (node.js) logic?
Hello! Can you please tell me how you implement logic in express applications that use DB, etc.?
There was this idea:
Code
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path')
, db = require('mongoose');
var app = express();
function init() {
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
}
db.connect(database).connection.once('connect', init);
But this code doesn't seem right to me. Please help.
Answer the question
In order to leave comments, you need to log in
In this context, I don't care, almost all libs have a buffer where all your requests go.
That. until either restores the connection to the database, everything falls into the buffer, until the error returns:
1) there is no possibility to connect to the database
2) out of memory
The question is not entirely clear and to which part of the code it relates, but I will try to answer.
The logic of working with the database should be in the models, because express is an mvc framework. For example, if you are using mongoose, then the logic can be organized in the form of class methods, hooks, and so on.
I would also advise you to move the definition of routes to a separate file (IMHO it's more convenient).
ps I read the tags
mannaro I wrote to you in the last question, look at what generates express ./appdir
and dance from it when. Here github.com/visionmedia/express/tree/master/examples are a bunch of examples of what and how to write.
Specifically, I do so, I do not remember where I saw it.
There are models.js
function defineModels(mongoose, fn) {
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var DataSchema = new Schema({
'user_id' : Number,
'title' : String,
'datetime' : Date
// и т.д.
});
mongoose.model('Data', DataSchema);
fn();
}
module.exports.defineModels = defineModels;
var express = require('express'),
mongoose = require('mongoose'),
models = require('./models.js');
// и т.д.
mongoose.connect('mongodb://localhost/db');
models.defineModels(mongoose, function() {
var Data = mongoose.model('Data');
})
Data.findOne({...})
, etc. Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question