从mongodb获取数据后呈现模板

时间:2018-04-27 15:14:26

标签: arrays node.js templates handlebars.js each

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"
    }
]

2 个答案:

答案 0 :(得分:0)

渲染必须在回调函数中:

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();
    });

});

});

答案 1 :(得分:0)

你快到了。

这种情况正在发生,因为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();
    });

});