Get the value of a given field from the latest document in Meteor collection

I need to get the value of myField from the latest entered document in Meteor collection.

{"id": meteor-generated, "myField": "value", "createdAt": <Date() generated 1st}
{"id": meteor-generated, "myField": "value_i_want", "createdAt": <Date() latest> }

I tired this which returned undefined. Thanks

Active.find({fields: {myField:1}}, {sort: {createdAt: -1}});
Active.fetchOne({}, {fields: {myField:1}, sort: {createdAt: -1}, limit: 1}).myField;

Edited to make it work :wink:

Did you mean Active.findOne(… OR Active.fetchOne(… which I could not find docs for?

And if you meant the former; then why when I run this command in the mongo terminal I get the following error.

findOne({}, {fields: {action:1}, sort: {createdAt: -1}, limit: 1}).action;

meteor:PRIMARY> db.activeTaskCol.findOne({}, {fields: {action:1}, sort: {createdAt: -1}, limit: 1}).action;
2016-03-05T06:56:25.770+1100 error: {
"$err" : “Can’t canonicalize query: BadValue Unsupported projection option: fields: { action: 1.0 }”,
“code” : 17287
} at src/mongo/shell/query.js:131

If you are using the mongo shell, you should just use plain projection operators. See manual.

This would look like:

db.activeTaskCol.findOne({}, {action:1}).sort({createdAt: -1}).limit(1)

Mongo shell is not the same syntax as Minimongo/meteor