简体   繁体   中英

List items in MongoDB array

I'm trying to list a series of paragraphs I have stored as an array in a document field "body". Where I have x items in the array, it outputs the whole field x times. If someone can point me in the right direction I'd so appreciate it. I know the issue is just where I have #{pages.body} at the end, because obviously that returns the whole field, but I'm not sure how to change it.

route:

exports.cont = function(db) {
    return function(req, res) {
        var collection = db.get('contents');
            collection.find({href:req.params.href},{},function(e,docs){
                res.render('cont', {
                    "cont" : docs
                });
            });
        };
};

display page in Jade:

each pages, i in cont
    .box
        h1 #{pages.title}
            .img
                img.body(src="#{pages.img}")
            .text
                each para, i in pages.body
                    p #{pages.body}

Solution:

each pages, i in cont
    .box
        h1 #{pages.title}
            .img
                img.body(src="#{pages.img}")
            .text
                each paragraph, i in pages.body
                    p #{paragraph.text}

MongoDB document setup:

{ 
    img: "xxxxxx",
    body:
        [
            { text: "xxxxxxx" },
            { text: "xxxxxxx" },
            { text: "xxxxxxx" }
        ]
}

If you want the option of HTML formatting in each paragraph, just replace the # before {paragraph.text} with !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM