ColetrainCodes ColetrainCodes - 1 year ago 66
HTML Question

How can I get a random document from a MongoDb collection, and then display each of the fields of that randomly selected document in HTML?

I am pulling a random document from a MongoDB Collection. Then I'm trying to display all the fields of that random document in HTML.

I am able to get a random document just fine, but when I try to display the fields of that document, they are all jumbled. Here's what I mean:

//function returns one random book from a collection of books
'book': function()
return BookList.find(randomBook);

This returns 1 random book from my collection. (I know the (randomBook) isn't correct, i'm just getting the point across. The function is a bit larger but it returns one random element from my book list)

I want to display the contents of THIS book in HTML.

When I do {{book.Title}}, {{book.Publisher}}, {{book.Etc}}, the values don't align because it's getting a random book every time. (as you would expect, the function gets a random book. So it gets a random title, random publisher, etc). I would like to get all the information from the same book.

I also know that in the helper function you can call:
return BookList.find()

And then in HTML the call
{{book 1}}
would return
[Object object]

I have tried
{{book 1.Title}}
, etc. But none of that works.

I guess what I'm asking is: How can I get a random book from a list of books, and then display each of the fields of that same book to HTML.

My project is an attempt to populate a table with a random book's information when you click a button. All the books are stored in a database, and I want to select a random book, display the Title, Publisher, etc in an HTML table.

Thanks for the help!

Answer Source

Use #with to set the data context then just use the keys directly:

<template name="hutch">
{{#with book}}
  Title: {{title}}
  Publisher: {{publisher}}

Then as @blueren suggests, use .findOne() to return a single book:

    return BookList.findOne(randomBook);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download