JarsOfJam-Scheduler
JarsOfJam-Scheduler

Reputation: 3149

How to display "fields"' value from the database in a Pug file?

I use MongoDBClient in Node.js, and Pug.

I would want to get all my pizzerias' name in my database. Thus, I wrote this line : collection.find({cook:'Pizza'}) to select all the pizzerias, and the attribute "name" exists.

But find returns a cursor, thus I can't directly use its return like that : var array_pizzerias_names = collection.find({cook:'Pizza'}).get('name'). (NB : I know the funciton get doesn't exist).

How could I do it ?

In my Pug file, I wrote these few lines :

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

Upvotes: 2

Views: 911

Answers (1)

JarsOfJam-Scheduler
JarsOfJam-Scheduler

Reputation: 3149

I found a solution.

MongoClient (require('mongodb').MongoClient) provides a find method signature which takes 2 parameters, and the second is a callback ; the last parameter of the latter is a cursor which have a method toArray.

The method toArray takes a callback ; its last parameter is the array containing all the results of the find, and can be used in Pug.

The below code works.

Node.js code (JavaScript file) :

        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 file :

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

Upvotes: 1

Related Questions