簡體   English   中英

從mongodb獲取數據后渲染模板

[英]Render template after fetching data from mongodb

app.get('/clients', (req, res) => {
    var clientArray;

    MongoClient.connect('mongodb://localhost:27017/Clients', (err, db) => {
        if (err) {
            return console.log('Unable to Connect');
        }
        console.log('Connected to Mongodb server');
        db.collection('Clients').find().toArray().then((docs) => {
            clientArray = JSON.stringify(docs, undefined, 2);
            // clientArray = docs;
            console.log(clientArray);
        }, (err) => {
            console.log("ERROR")
        });
        db.close();
    });
    res.render('clients.hbs', {
        infoArray: clientArray,
        name: 'Harshit'
    });
});

在從mongodb數據庫獲取所需數據之前,將在此處調用res.render函數。 我想將以數組形式獲取的數據傳遞到車把模板。

{{#each infoArray}}
        <h1>{{this.name}}</h1>
        {{this.region}}
        {{/each}}

在這里,我嘗試遍歷呈現的數組並顯示數據。感謝您的幫助。 數組的結構

[{
        "name": "harshit",
        "region": "delhi"
    },
    {
        "name": "mendax",
        "region": "ecuador"
    }
]

渲染必須在回調函數中:

app.get('/clients', (req, res) => {
var clientArray;

MongoClient.connect('mongodb://localhost:27017/Clients', (err, db) => {
    if (err) {
        return console.log('Unable to Connect');
    }
    console.log('Connected to Mongodb server');
    db.collection('Clients').find().toArray().then((docs) => {
        clientArray = JSON.stringify(docs, undefined, 2);
        // clientArray = docs;
        console.log(clientArray);
         db.close();

        res.render('clients.hbs', {
          infoArray: clientArray,
          name: 'Harshit'
        });

    }, (err) => {
        console.log("ERROR")
         db.close();
    });

});

});

你快到了。

這是MongoClient.connect(..是異步的。所以您在此之前執行res.render

您需要的是,只需將res.render該塊內

app.get('/clients', (req, res) => {
    var clientArray;

    MongoClient.connect('mongodb://localhost:27017/Clients', (err, db) => {
        if (err) {
            return console.log('Unable to Connect');
        }
        console.log('Connected to Mongodb server');
        db.collection('Clients').find().toArray().then((docs) => {
            clientArray = JSON.stringify(docs, undefined, 2);
            // clientArray = docs;
            res.render('clients.hbs', {
                infoArray: clientArray,
                name: 'Harshit'
            });
        }, (err) => {
            console.log("ERROR")
        });
        db.close();
    });

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM