刚开始学习nodejs,对js也很陌生,并四处寻找最佳实践并遇到了这个问题: https://stackoverflow.com/a/15572522/1203349
我正在使用这种结构开发应用程序。他建议将db调用放在相应的 model / model.js 文件中
例如。
使用他的样本,假设我想要一个完整的博客列表
在 routes / blog / index.js 中,我应该执行以下操作:
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.
});
}
和 models / blog.js ,
....
exports.<every function for crud>?
示例实现将不胜感激。
答案 0 :(得分:1)
我希望通过以下代码解决您的问题。
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'));
});
完成后,您可以将CURD功能移动到其他文件。
答案 1 :(得分:1)
Amol的答案很好,这应该可以帮助您入门,但听起来您在模块方面存在代码组织问题。
对于项目中的本地模块,假设您有一个名为models.js
的文件,它看起来像:
// models.js
function Customer () {
// some properties
}
function Invoice () {
// some properties
}
module.exports = {
Customer: Customer,
Invoice: Invoice
}
然后在您的主应用程序中,您将访问您的模型,如下所示:
// app.js
var models = require('./models')
myCustomer = new models.Customer();
myInvoice = new models.Invoice();
希望有所帮助,
亚伦