如何在Pug文件中显示数据库中的“fields”值?

时间:2016-12-25 16:46:00

标签: node.js mongodb-query pug

我在MongoDBClientNode.js使用Pug

我想在我的数据库中获取所有比萨饼店的名字。因此,我写了这一行:collection.find({cook:'Pizza'})来选择所有比萨店,并且存在属性“name”。

但是find返回一个游标,因此我不能直接使用它的返回:var array_pizzerias_names = collection.find({cook:'Pizza'}).get('name')。 (注意:我知道功能get不存在)。

我怎么能这样做?

在我的Pug文件中,我写了几行:

        - for(var i = 0; i < array_pizzerias_names.length; i++) {
            p=array_pizzerias_names[i].name
        - }

1 个答案:

答案 0 :(得分:1)

我找到了解决方案。

MongoClientrequire('mongodb').MongoClient)提供find方法签名,其中包含2个参数,第二个是回调;后者的最后一个参数是cursor,它有一个方法toArray

方法toArray进行回调;它的最后一个参数是array,其中包含find的所有结果,可以在Pug中使用。

以下代码有效。

Node.js代码(JavaScript文件):

        collection.find({cuisine: speciality}, (error, cursor) => {
            handleError(error, res);

            cursor.toArray((error, array_results) => {
                handleError(error, res);

                app.locals.speciality = speciality;
                app.locals.array_documents = array_results;
                res.render("speciality.pug");

            });
        });

Pug文件:

doctype html
html(lang='fr')
    head
        title='Speciality'
        body
            h1 Speciality : #{speciality} - Number of buildings : #{array_documents.length}
            - for(var i = 0; i < array_documents.length; i++) {
                p=array_documents[i].name + " - Address : " + array_documents[i].address.street + " " + array_documents[i].borough + ", building n°" + array_documents[i].address.building
            - }