1

刚开始学习 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>?

示例实现将不胜感激。

4

2 回答 2

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 函数移动到不同的文件中。

于 2013-09-19T06:31:41.723 回答
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();

希望有帮助,
亚伦

于 2013-09-19T15:28:07.070 回答