简体   繁体   English

在Mongo流星中发现价值

[英]Find Value in Meteor Mongo

I am new to web programming and have recently been playing around with Meteor and MongoDB. 我是Web编程的新手,最近一直在与Meteor和MongoDB一起玩耍。

I have a form which sends data to mongo and using the query below have retrieved the most recently entered value: 我有一个将数据发送到mongo的表单,并且使用下面的查询检索了最近输入的值:

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() ? 我应该使用distinct()吗?

Thanks! 谢谢!

If you are looking to retrieve a field out of the returned document, you can specify as much using the fields option: 如果要从返回的文档中检索字段,则可以使用fields选项指定尽可能多的内容:

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: 作为一个更具体的示例,我有一个包含用户名,名称,_id等的用户数据库,如果我只想将用户名存储在另一个变量中,则可以这样进行:

> 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: 请注意,如果要提取特定ID或其他选择器的数据,则需要在选择器中填写数据:

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

See the Meteor Mongo.Collection.find documentation for more information. 有关更多信息,请参阅Meteor Mongo.Collection.find文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM