This Meteor code tries to find the last document in a collection.
.find({userId: this.userId}, {sort: {createdAt: -1}, limit: 1});
But since all the documents are in chronological order, I thought to remove the createdAt field, so once that is 'deleted', Is there a "not expensive" way to return just the last entered document? Thanks
{userId: 'someId', info: 'someInfo'}
myCol.findLast().info; <--- my wish list
$last(aggregation) in the docs first does sorting among other things
edit
An attempt to utilise the idea given by Stephen Woods;
server.js
MyCol._ensureIndex({createdAt: -1});
MyCol.before.insert(function (userId, doc) {
doc.userId = userId;
createdAt = Date.now();
});
Meteor.publish('myCol', function () {
return MyCol.findOne({userId: this.userId});
});
I'm going to make the assumption that by expensive you mean execution time. In that case, you want a createdAt field, a secondary index on createdAt, and to use a findOne() statement. To create the index on createdAt for your collection, do:
myCol._ensureIndex({ createdAt: -1 });
Then in your publish:
Meteor.publish('myCol', function () {
return MyCol.find({userId: this.userId}, { sort: { createdAt: -1 } });
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With