flimflam57
flimflam57

Reputation: 1334

Select the last document from mongo collection in meteor

I want the latest document in the query. Below I'm getting those documents whose name is coming from the variable 'personalFullName, then sorting them by a field called 'RecordID' (this field has higher numbers as later date entries), then grab the last one. I want the latest (the one with the largest RecordID number) entry in this query:

Programs.find({ FullName: personalFullName }, { sort: { RecordID: 1 }, limit: 1}).fetch().pop();

I'm getting an error that it's exceeding the call stack size.

Upvotes: 0

Views: 375

Answers (1)

biofractal
biofractal

Reputation: 19143

If you are comfortable using the meteorhacks:aggregate package then you could always publish the item(s) you want using the mongo aggregate pipeline, perhaps something like this (code is coffeescript):

Meteor.publish 'latestPrograms', (personalFullName)->
    return unless personalFullName?
    check personalFullName, String
    pipeline = [
        {$match:{'Fullname': personalFullName}}         
        {$sort: {'RecordID': 1}}
        {$group:{'_id':{Fullname: '$Fullname'}, RecordID:{$last:'$RecordID'}}}
        {$limit:1}
    ]
    @added 'latestPrograms', Random.id(), item for item in programs.aggregate pipeline
    @ready()

You can then grab the data by subscribing to the latestPrograms pseudo collection. Here is an example using a iron router route:

Router.route '/home', 
    name: 'home'
    template:'homepage'
    waitOn:->
        Meteor.subscribe 'latestPrograms', personalFullName
    data:->
        {latestPrograms: latestPrograms.find()}

Upvotes: 1

Related Questions