Mongo results always empty

I am trying to fetch data from mongo but the result set is always empty.

The collection I’m trying to access is meteor/offers. I created the collection in the mongo database myself using a mongodb client. I am connecting to the mongo instance that’s launched when running meteor run. The collection has 1 document that I created.

I can’t understand why it’s not fetching the document. Do I need to create a Method to fetch the data? I have read through Methods, Collection, and the React example but I’m still having problems.

Also why do I have to create the database myself? The docs say calling Mongo.Collection “sets up a collection (a storage space for records, or “documents”)”. It doesn’t create the collection on my end hence why I created it myself with the mongo client.

My code is below

imports/api/offers.js

import { Mongo } from 'meteor/mongo'

export const Offers = new Mongo.Collection('offers')

imports/ui/components/OfferListComponent.js

import { Meteor } from 'meteor/meteor'
import React from 'react'
import { withTracker } from 'meteor/react-meteor-data'

import { Offers } from '../../api/offers'
import OfferList from '../components/OfferList'

export default withTracker(({ id }) => {
    const handle = Meteor.subscribe('offers', id)

    return {
        currentUser: Meteor.user(),
        loading: !handle.ready(), 
        offers: Offers.find().fetch(),
    }
})(OfferList)

creating an instance of a collection (new Mongo.Collection('name')) will connect to the existing collection in the database, so no worries there.

As for the data not appearing, Have you got a publication set up with Meteor.publish? or do you have the autopublish package installed?

I don’t have autopublish installed. I have created a publication:

server/main.js

import { Meteor } from 'meteor/meteor'
import { Offers } from '../imports/api/offers'

Meteor.publish('offers', () => Offers.find())

Meteor.startup(() => {
  ServiceConfiguration.configurations.remove({
    service: 'facebook'
  })

  ServiceConfiguration.configurations.insert({
    service: 'facebook',
    appId: '*********',
    secret: '********'
  })
})

I refactored some code while I waited for someone to reply here and since checking all is working fine. I may have had a typo somewhere so this may entirely be my fault. All good for now :slight_smile:

Thank you for your time in helping to solve this problem.

1 Like

Glad it started working in the end

I’ll just note to be careful with arrow functions around Meteor features like publications. Because of the this binding and Meteor’s use of Fibers, it can cause odd bugs, so we just avoid arrow functions around Meteor functions

1 Like

I had the same issue. The thing I was missing was to import the js file with the Meteor.publish() call in the registration_api.js file so that it gets executed. Took me about a day to figure this out. doh!