Reputation: 729
I want to get last inserted item in minimongo. currently i'm doing it in this way (code on client side):
addBook()
{
BookCollection.insert(
this.book , ( err , insertedBook_id )=>
{
this.book_saved = true;
console.group('Output:')
console.log(err);
console.log( insertedBook_id );
console.log(
BookCollection.find({_id: insertedBook_id})
.fetch()
);
console.groupEnd();
//this.router.navigate(['/book', insertedBook_id]);
}
);
}
Output in console:
undefined
t6Lwrv4od854tE7st
[]
As you can see, when i redirect to newly created page, i cant find a book, but in mongo shell i clearly see that record was added. Should i wait for some event like BookCollection.insert(this.book).then( . . . )
? Please help me!)
When i go back to the 'all books page', i see new record and can click, all works normal, no errors.
In the /book controller:
ngOnInit()
{
this.sub = this.curr_route.params.subscribe(
params=>
{
this.book = BookCollection.findOne( params[ '_id' ] ); // .fetch() == []
//if(!this.book)
// this.router.navigate(['/books']);
Meteor.subscribe(
'book' , params[ '_id' ] , ()=>
{
this.book = BookCollection.findOne( params[ '_id' ] );
} , true
)
console.groupCollapsed( 'BookDetailsCardComponent log data:' )
console.group( 'Book:' );
console.log( this.book );
console.groupEnd();
console.groupEnd();
} , true
);
}
Upvotes: 0
Views: 260
Reputation: 426
This is probably a timing issue. The _id
is most likely created and returned immediately while the actual data is inserted into the database, which would explain why doing a find()
on that _id
right away comes back as an empty array.
Is there a reason you are doing your insert from the client rather than doing it on the server and using a Meteor method to initiate it? Changing to this approach might resolve your issue.
Upvotes: 1