简体   繁体   中英

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:

Template.hutch.helpers(
{
    //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}} , {{book[1].Title}} , {{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!

Assuming your random book document looks like :

{
  bookName: "TheRandomBook",
  bookAuthors: "RandomAuthor",
  bookPublishedYear: 1969,
  ....

}

helper.js:

Since you want only one book, use findOne instead of find since findOne will return you exactly one object, whereas find will return a cursor to iterate over the objects.

getRandomBook: function(){
   return books.findOne();
}

showBooks.html:

<htmlTag> {{getRandomBook.bookName}} </htmlTag>
<htmlTag> {{getRandomBook.bookAuthor}} </htmlTag>
<htmlTag> {{getRandomBook.bookbookPublishedYear}} </htmlTag>

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

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

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

Template.hutch.helpers({
  'book'(){
    return BookList.findOne(randomBook);
  }
});

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