【问题标题】:Clean MongoDB/Node.js/Express code and routes清理 MongoDB/Node.js/Express 代码和路由
【发布时间】:2020-05-14 08:27:28
【问题描述】:

不久前,我开始使用 MongoDB 和 Node.js 学习数据库,我正在尝试找到一种方法来使用 没有 mongoose 的 Express 路由。我想使用 Express 路由插入数据并使用干净的代码导出不同的模块。问题是我不能写路线 如下,因为在我的 index.js 文件中,“db”当然没有定义,显然我不能像猫鼬一样在函数“client.connect”之外将数据插入到我的“db”中。我是否必须将我的数据库与我的所有帖子连接到一个文件中,还是有特定的方法可以做到这一点? (对不起我的英语,我正在学习它)。

App.js:

const express = require('express');
const app = express();
const expressLayouts = require('express-ejs-layouts');
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

//EJS
app.use(expressLayouts);
app.set('view engine', 'ejs');

//Styles
app.use('/public', express.static('public'));

//Bodyparser
app.use(express.urlencoded({extended: false}));


//Connect to DB
const url = 'mongodb://localhost:27017/shopping'
const dbName = 'shopping';
const client = new MongoClient(url);

client.connect((err)=>{
    assert.equal(null, err);
    console.log('connected to db...');

    app.use('/', require('./routes/index'));    

    const db = client.db(dbName);
});

//Server
app.listen(3000, ()=>{console.log("Listening to port 3000")});

index.js(路由):

const express = require('express');
const router = express.Router();

//Get home page
router.get('/', (req, res)=>{
    res.render('shop/index')
});

router.get('/posts', (req,res)=>{
    res.render('posts')
});

router.post('/posts',(req,res)=>{
    db.collection('users').insertOne({'name': req.name, 'password': req.password});
});

module.exports = router;

【问题讨论】:

    标签: node.js database mongodb express routes


    【解决方案1】:

    Index.js 应该包含一个函数来传递你的 mongo 客户端。例如:

    let mongoClient
    router.passMongoClient = function(clientIn){
       mongoClient = clientIn
    }
    

    然后在你启动你的客户端之后,通过你的新函数传入它

    const router = require(./router)
    
    client.connect((err)=>{
        assert.equal(null, err);
        console.log('connected to db...');
    
        app.use('/', require('./routes/index'));    
        const db = client.db(dbName);
        router.passMongoClient(db)
    });
    

    这是基本思想。您可能希望以不同的方式构建您的代码。我等待启动我的 http 服务器,直到我从 mongodb 客户端收到它已连接的回调。在一定程度上取决于您的用例。

    【讨论】:

    • 谢谢!我想我明白了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    • 2015-01-30
    • 2019-09-02
    • 2015-01-03
    • 1970-01-01
    • 2014-03-20
    相关资源
    最近更新 更多