[solved]Retrieving data from my collection


#1

I’ve searched everywhere but for some reason I can’t get this to work.
I have the following data inside my MongoDB:

{
    "_id" : "CKwFAQiLqxKsvLNRM",
    "0" : {
        "advert" : {
            "reference" : 102080138,
            "type" : "Terrenos",
            "n_beds" : "N/d",
           ( . . . )
        }
    },

I want to access the field “advert” and display it in one ordered list. But I cant manage to access the field.
I’ve tried Collection.findOne() but I get several errors.
If someone could help me with this would be great.
thanks in advance


#2

Can you please share the errors you are getting ?


#3

Exception in template helper: TypeError: Cannot convert undefined or null to object

my HTML

  <div class="posts">
        {{#each imovelURL}}
            <p><a href='#'>Imovel</a></p>
        {{/each}}
    </div>

my JS

Template.imoveis.helpers({
    imovelURL: function() {
        let arr = []
        for(let c = 0; c < 2; c++) { // Print 2 fields 'advert' 
            arr.push(Object.keys(Object.values(adverts.find().fetch()['0'])[c]))
        }
        return arr;
},
},)

I’m trying to print the field ‘advert: {’ on the HTML, click on it and then print a table.
You’re probably wondering what is wrong with this code syntax. my bad


#4

Hi,
Your document structure could be improved imo, although I don’t really know your need; I don’t understand why you put “0” as key when an array could do the stuff way better. You should use findOne() instead of find().fetch()[0] but I assume this was just for testing purpose.

Have you setup publication/subscription ?
Else, your MongoDB on client side will contains no data, meaning .find() will return undefined unless you use autopublish package.
Have a look to https://docs.meteor.com/api/pubsub.html

You can use https://atmospherejs.com/meteortoys/allthings to easily visualize your data on clientside.

I don’t think this, will put 2 advert fields in your array


#5

Thanks @redrelay!
Indeed I need to improve my document structure and meteor concepts in general.
Changing find().fetch()[0] to findOne() solved my problem of accessing the field advert.
I did setup pub and sub and removed the autopub package.
“meteortoys:allthings” is extremely helpful! Thanks!

My problem is solved :slight_smile: