Bren
Bren

Reputation: 273

Return contents of one field (an array) from Mongodb document in Meteor

I am working in Meteor and trying to retrieve just the contents of one field in a Mongodb document. This particular field is an array. I've read the Mongo docs and several related questions, but my projection just isn't working. This is what I have:

User adds to array using the following form:

Template.One.events({
    'submit form': function(e) {
        e.preventDefault();
        var currentId = this._id
        var oneProperties = {
            selections: $(e.target).find('[name=selection]').val()
        };
        Charts.update(currentId, ($addToSet: selections}, function() {});
    }
});

Resulting document:

{
    "_id": "some ID",
    "selections": ["A","B"]
}

Refer to array in a helper for a different template to access documents from a different collection.

Template.Two.helpers({
    comps: function() {
        var selected = Charts.findOne({_id:this._id}, {selections:1, _id:0});
        return Companies.find({ticker: {$in: selected}});
    }
});

When I run the Charts.findOne query above directly in the console, it returns the entire document, with no limitations.

If I replace Charts.findOne({_id:this._id}, {selections:1, _id:0}); with simply ["A","B"], then everything else works perfectly. So I know it is the projection itself. I also can't tell if this query will return just need the array, which is what I need, or the name selections: as well.

Any thoughts very appreciated.

Upvotes: 1

Views: 1635

Answers (1)

chridam
chridam

Reputation: 103365

Try accessing the selections field of the document, that should give you the array directly, not the entire document:

var selected = Charts.findOne({_id:this._id}, {selections:1, _id:0});

would give you { "selections": ["A","B"] }

But

var selected = Charts.findOne({_id:this._id}, {selections:1, _id:0}).selected;

will give you the needed array

["A","B"]

Upvotes: 2

Related Questions