I have a collection that gets initialized and filled successfully as the app starts, I could see it populated in MiniMongo as well with 4 records.
Now when I try to fetch or update a record on the server, I find the collection to be always empty.
Tried .find().fetch()
and it always returns an empty array, though it’s already been populated.
What’s happening guys?
Hi @samicodes, welcome to the forums!
Can you post the code where you fill the database? including the file paths?
My first guess is that you are only running insert on the client and not the server.
Hopefully you just need to import the file from the server
Thank you @coagmano
So I fill the database during a publication
Meteor.publish('suppliers.get', function (supplierId) {
// here I make an API call through an async poll function
// the API response is an array which I loop over and then do:
this.changed('suppliers', doc.id, doc); // or this.added
})
There doesn’t seem to be any file paths include.
The above was taken from the Meteor guide on advanced publications and calling REST APIs,
and it results in having a populated suppliers
collection in MiniMongo in the browser.
Hope this helps you get better insight on the problem.
Thanks, that helps a lot.
Short version
If you want to access data on the server, you probably want to populate/update the database directly, with Collection#insert
, and return a cursor in the publication:
export const Suppliers = new Mongo.Collection('suppliers');
function syncWithRemote() {
const data = HTTP.get(/* some resource */);
for (const entry of data) {
Suppliers.upsert({ _id: entry.id }, entry);
}
}
Meteor.setInterval(syncWithRemote, 10000);
Meteor.publish('suppliers.get', function (supplierId) {
return Suppliers.find({ supplierId: supplierId });
});
Long version
The issue here is using this.added/changed
to populate the database.
In reality, this.added/changed
sends a DDP message to the client to say that a document has been added and the client should reflect this in minimongo,
Key point being that it sends messages to the client; it does not talk to MongoDB.
Normally, you would return a Mongo cursor in a publication function. Meteor then creates an observer that watches the database for changes matching the given query and automatically calls this.added/changed/removed
, sending DDP messages to keep the client in sync.
This means you can poll and update the data in MongoDB separate from the publication, and whenever the underlying data changes it will notify the client/minimingo via DDP messages.
In my example code, I’m using Meteor’s API, but depending on size you might want to do a bulk update using the raw MongoDB nodejs driver:
Suppliers.rawCollection().initializeUnorderedBulkOp()
3 Likes
Thanks a lot @coagmano
Awesome explanation! I read more into how Meteor collections work guided by your response and it makes sense now.
Solid help there!