0

Hello I just create skeleton meteor js application and write the following code in main js file:

People = new Meteor.Collection("people");

People.insert({name: 'test'});
console.log(People.find().fetch());

I reload the page and record was inserted in mongodb and I see it in mongodb command line but when I try to fetch result from database receive empty array ?

1 Answer 1

1

Collection methods are asynchronous: this basically means that they do not stop the process until they are finished. Therefore, in your case, you are trying to fetch the previously inserted person without waiting for said insertion to be over.

This is why Collection.insert can take an optional callback function as a parameter, which will be called as soon as the insert is finished:

People = new Meteor.Collection("people");

People.insert({name: 'test'}, function () {
  // this will be printed after the insert is done
  console.log(People.find().fetch());
});
// this will be printed after the insert is started, and (probably) before it is finished.
console.log('Insertion started!');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.