【问题标题】:NodeJS app with express and mongoDB带有 express 和 mongoDB 的 NodeJS 应用程序
【发布时间】:2011-12-15 05:08:24
【问题描述】:

我正在编写这个迷你 RESTful 应用程序,它接受对不同 URL 的请求。为此,我使用 nodejs,并表示设置不同的路径。作为数据库,我打算使用 monogoDB(christkv 的 node-mongodb-native)。

我的代码(不包括 mongo 尝试)如下所示:

app.js

/**
 * Module dependencies.
 */
var express = require('express')
    , routes = require('./routes')
var app = module.exports = express.createServer();

var Db = require('mongodb').Db;
var Server = require('mongodb').Server;
var client = new Db('test', new Server('127.0.0.1', 27017, {}));    

// Configuration

app.configure(function() {
    app.set('views', __dirname + '/views');
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(app.router);
    app.use(express.static(__dirname + '/public'));
});

app.configure('development', function() {
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function() {
    app.use(express.errorHandler());
});

var insertData = function(err, collection) {
    collection.insert({name: "Kristiono Setyadi"});
    collection.insert({name: "Meghan Gill"});
    collection.insert({name: "Spiderman"});
}



// Routes
app.post('/', routes.syncServiceIndex);

app.post('/syncService', routes.synchServicePost);
app.get('/syncService/:syncServiceUser/sync', routes.synchServiceSync);
app.post('/syncService/:syncServiceUser/push', routes.synchServicePush);
app.del('/syncService/:syncServiceUser', routes.synchServiceDel);

app.post('/syncService/:syncServiceUser/contacts/push', routes.synchServiceContactsPush);
app.get('/syncService/:syncServiceUser/contacts/sync', routes.synchServiceContactsSync);

app.post('/syncService/:syncServiceUser/contacts/', routes.synchServiceContactsPost);
app.get('/syncService/:syncServiceUser/contacts/:contactId', routes.synchServiceContactsGet);
app.put('/syncService/:syncServiceUser/contacts/:contactId', routes.synchServiceContactsPut);
app.del('/syncService/:syncServiceUser/contacts/:contactId', routes.synchServiceContactsDel);

app.listen(3000);



console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);

为了将不同的组件保存在不同的文件中,这是我的文件,其中包含每个 URL 的代码:

index.js

//var ObjectID = db.bson_serializer.ObjectID;
exports.syncServiceIndex = function(req, res) {
    console.log('syncServiceIndex');
    //console.log("BODY:" + JSON.stringify(req.body));

    res.statusCode = 200;
    res.send("OK\n");
};

exports.synchServicePost = function(req, res) {
    console.log('synchServicePost');
    console.log("BODY:" + JSON.stringify(req.body));
    var jsonObject = JSON.parse(JSON.stringify(req.body));
    res.statusCode = 200;
    res.send("OK\n");
};

exports.synchServiceSync = function(req, res) {
    console.log('synchServiceSync');
    res.statusCode = 200;
    res.send("OK\n");
};

exports.synchServicePush = function(req, res) {
    console.log('synchServicePush');
    res.statusCode = 200;
    res.send("OK\n");
};

exports.synchServiceDel = function(req, res) {
    console.log('synchServiceDel');
    res.statusCode = 200;
    res.send("OK\n");
};

exports.synchServiceDel = function(req, res) {
    console.log('synchServiceDel');
    res.statusCode = 200;
    res.send("OK\n");
};

exports.synchServiceContactsPush = function(req, res) {
    console.log('synchServiceContactsPush');
    res.statusCode = 200;
    res.send("OK\n");
};

exports.synchServiceContactsSync = function(req, res) {
    console.log('synchServiceContactsSync');
    res.statusCode = 200;
    res.send("OK\n");
};

exports.synchServiceContactsPost = function(req, res) {
    console.log('synchServiceContactsPost');
    res.statusCode = 200;
    res.send("OK\n");
};

exports.synchServiceContactsGet = function(req, res) {
    console.log('synchServiceContactsGet');
    res.statusCode = 200;
    res.send("OK\n");
};

exports.synchServiceContactsPut = function(req, res) {
    console.log('synchServiceContactsPut');
    res.statusCode = 200;
    res.send("OK\n");
};

exports.synchServiceContactsDel = function(req, res) {
    console.log('synchServiceContactsDel');
    res.statusCode = 200;
    res.send("OK\n");
};

从我一直在检查的一些示例代码中看到,我应该只使用一个打开的连接,也就是说我应该将所有代码都放在

client.open(function(err, pClient) {

});

打电话。我遇到的问题是我不确定如何传递客户端或集合,以便我可以使用 index.js 文件中的数据库。有没有办法在当前布局中做到这一点,还是我必须移动一些东西?

【问题讨论】:

    标签: mongodb node.js express


    【解决方案1】:

    您可以将所有路由包装到回调中并在中间件中设置req.mongoClient = pClient,例如:

    client.open(function(err, pClient) {
      clientMiddleware = function (req, res, next) {
        req.mongoClient = pClient;
        next();
      }
      // your routes here, with clientMiddleware
      app.post('/', clientMiddleware, routes.syncServiceIndex);
      app.post('/syncService', clientMiddleware, routes.synchServicePost);
      app.get('/syncService/:syncServiceUser/sync', clientMiddleware, routes.synchServiceSync);
      // etc.
    });
    

    您现在可以在所有路由中使用req.mongoClient 获取客户端。

    【讨论】:

    • 为什么要在 client.open 回调中封装路由?如果我也使用 mongoskin,我是否必须这样做?
    • 如果您希望 mongoClient 在路由/控制器中易于访问,您可以这样做。你不需要这样做,这是一个偏好问题。
    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-11
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多