flimflam57
flimflam57

Reputation: 1334

Error with setting variable in property name in Mongo when using query

I have a collection called Programs in Mongo where one document looks like this (I'm in Meteor):

{ id: "gMyxyez43sxya",
 .
 .
 Teachers: { 
             Week1: { Sunday: "SAM", Monday: "GEORGE" },
             Week2: { Sunday: "FIONA", Monday: "JEFFERS" }
           },
 CampYear: "ssipc16",
 }

The "Week1", "Week2" properties I need as a variable. The variable is calculated here:

var week = "Week" + Session.get('CurrentWeek').substr(0, 1); //this would render 'Week1', for example
var teacher = document.getElementById('sunday').value;

The query that I would need is this:

Programs.find({ "Teachers.week.Sunday": teachers });

But that won't work. So I built the object like this:

var query = { Teachers: {} };
query.Teachers[week].Sunday = teacher;

Then:

Programs.find(query).count();

But I'm getting a type error 'Uncaught TypeError: Cannot set property 'Sunday' of undefined'.

I also tried it like this:

query.Teachers[week] = { 'Sunday': teacher };
Programs.find(query).count();

There's no error but it keeps calculating a count of 0 every time.

How to make this work?

Upvotes: 0

Views: 51

Answers (1)

flimflam57
flimflam57

Reputation: 1334

I found the solution: I needed to build it like this:

var teacher = document.getElementById('sunday-lessons-students').value;
var week = "Week" + Session.get('CurrentWeek').substr(0, 1);
var query = {};
query['Teachers.' + week + '.Sunday'] = teacher;
console.log(Programs.find(query).count());

Upvotes: 2

Related Questions