findOne() with _id works, but find() doesnt?

Why does


return undefined, but if I use findOne() with the _id, it properly returns the value of location.name. Shouldnt they both work…?

Because find() is a cursor and findOne() is a single object. If you want all the ids of the cursor:

Collection.find().map(function (doc) {
  return doc._id;
})
1 Like

find returns a cursor (see the official documentation for find) while findOne actually fetch a document matching the selector.

1 Like

How would I access the name value using a cursor then? Note that im not returning this data to a template.

if your selector is based upon the _id field the right way to go is findOne wich will returns you the sought document or undefined in case it doesn’t exists.

The thing about using find is that you cannot know in advance how many documents it could retrieve (this mainly depends on both the selector being used and the size of the DB…).
So the right way to deal with a cursor is some sort of loop.
The example given by @cordiv is a good one. Another solution is to use the forEach or the other method available on a Mongo Cursor object.

Another possibility is to rely on the underscorejs (_) methods like _.each or _.map or anything else which work well also with cursors.

1 Like

Can you explain what you’re trying to accomplish a little more? I don’t know what you’re trying to do

1 Like

Im implementing googles WebGl Globe in Meteor. I got the globe to at least show up and used some static data in the methods to add points on the globe. Im trying to instead pull the data from a Collection for reactive/realtime features if the data changes.

findOne() is find().fetch()[0]. See meteor docs

Equivalent to find(selector, options).fetch()[0] with options.limit = 1

I guess you have to use find().observe in a way like:

Points.find().observe({
    added: function(doc) {
       // add point here
    },
    changed: function(doc, oldDoc) {
       // get point and modify
    },
    removed: function(doc) {
       // remove point from globe
    }
})