Find Value in Meteor Mongo

故事扮演 提交于 2019-12-24 22:37:42

问题


I am new to web programming and have recently been playing around with Meteor and MongoDB.

I have a form which sends data to mongo and using the query below have retrieved the most recently entered value:

database.findOne({}, {sort: {'timeStamp' : -1}, limit:1})

Which is cool however, I only want the value of a specific variable not the entire entry so I can use that variable with calculations elsewhere.

Does anyone have an pro tips? Should I use distinct()?

Thanks!


回答1:


If you are looking to retrieve a field out of the returned document, you can specify as much using the fields option:

database.findOne({}, {sort: {'timeStamp' : -1}, limit:1, fields: {'myField': 1, _id: 0})

That will retrieve an object in format like this:

{'myField': 'value of myField'}

So if you want to interact directly with that you can access it like so:

var myVar = database.findOne({}, {sort: {'timeStamp' : -1}, limit:1, fields: {'myField': 1, _id: 0}).myField

As a more concrete example, I have a user database with username, name, _id, etc., and if I just want to store a user's name in another variable, I can do so like this:

> a = Meteor.users.findOne({}, {fields: {name: 1, _id: 0}}).name;
> a
<- "Bob" // returned "Bob"

Note that if you want to pull the data for a specific ID or other selector, you'll need to fill that in in the selector:

database.findOne({_id: "myId"}, ...)

See the Meteor Mongo.Collection.find documentation for more information.



来源:https://stackoverflow.com/questions/29458095/find-value-in-meteor-mongo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!