[solved]Retrieving data from my collection

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

Can you please share the errors you are getting ?

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

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 Publish and subscribe | Meteor API Docs

You can use The trusted source for JavaScript packages, Meteor resources and tools | Atmosphere to easily visualize your data on clientside.

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

2 Likes

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: