在 Meteor Mongo 中寻找价值 [英] Find Value in Meteor Mongo
问题描述
我是网络编程的新手,最近一直在玩 Meteor 和 MongoDB.
I am new to web programming and have recently been playing around with Meteor and MongoDB.
我有一个向 mongo 发送数据的表单,并使用下面的查询检索了最近输入的值:
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.
有人有专业提示吗?我应该使用 distinct()
吗?
Does anyone have an pro tips? Should I use distinct()
?
谢谢!
推荐答案
如果您想从返回的文档中检索字段,您可以使用 fields
选项指定尽可能多的字段:>
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
举一个更具体的例子,我有一个包含用户名、名称、_id 等的用户数据库,如果我只想将用户名存储在另一个变量中,我可以这样做:
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"
请注意,如果您想为特定 ID 或其他选择器提取数据,则需要在选择器中填写:
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"}, ...)
有关详细信息,请参阅 Meteor Mongo.Collection.find 文档.
See the Meteor Mongo.Collection.find documentation for more information.
这篇关于在 Meteor Mongo 中寻找价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!