2017-05-25 45 views
0

我有一個具有以下格式的文檔:

{ 
"Students" : { 
    "Week1" : { 
     "Monday" : [ 

     ], 
     "Tuesday" : [ 

     ], 
     "Wednesday" : [ 

     ], 
     "Thursday" : [ 

     ], 
     "Friday" : [ 

     ], 
     "Saturday" : [ 

     ], 
     "Sunday" : [ 

     ] 
    }, 
    "Week2" : { 
     "Sunday" : [ 

     ], 
     "Monday" : [ 

     ], 
     "Tuesday" : [ 

     ], 
     "Wednesday" : [ 

     ], 
     "Thursday" : [ 

     ], 
     "Friday" : [ 

     ], 
     "Saturday" : [ 

     ] 
    }, 
    "Week3" : { 
     "Sunday" : [ 

     ], 
     "Monday" : [ 

     ], 
     "Tuesday" : [ 

     ], 
     "Wednesday" : [ 

     ], 
     "Thursday" : [ 

     ], 
     "Friday" : [ 

     ], 
     "Saturday" : [ 

     ] 
    }, 
    "Week4" : { 
     "Sunday" : [ 

     ], 
     "Monday" : [ 

     ], 
     "Tuesday" : [ 

     ], 
     "Wednesday" : [ 

     ], 
     "Thursday" : [ 

     ], 
     "Friday" : [ 

     ], 
     "Saturday" : [ 

     ] 
    }, 
    "Week5" : { 
     "Sunday" : [ 

     ], 
     "Monday" : [ 

     ], 
     "Tuesday" : [ 

     ], 
     "Wednesday" : [ 

     ], 
     "Thursday" : [ 

     ], 
     "Friday" : [ 

     ], 
     "Saturday" : [ 

     ] 
    } 
    } 
} 

我想要把一些元素融入Students.Week1.Monday動態使用Week1作爲變量。所以我想這樣構建它:

var dbNames = ['Zoe', 'Billy', 'Joey']; 
var week = Week1; // week is dynamic entry 
var query1 = {}; 
query1['Students.' + week + '.Monday'] = '$in: ' + dbNames; 
Programs.update({ _id: teacherid }, { $push: query1 }); 

我搞砸了。任何幫助表示讚賞。

回答

1

你可以動態創建對象來解決問題

var query = {}; 
var week = "DYNAMIC_VAL"; // Replace this 
var day = "Monday"; // Dynamic Day 
var dbNames = ['Zoe', 'Billy', 'Joey']; 
query['Students'] = {}; 
query['Students'][week] = {}; 

// query['Students'][week][day] = { '$in': dBNames } // As per your query. 
// but it should not work, 
// if you want to push all elements of dbNames then you can use $each instead of $in 

query['Students'][week][day] = { '$each': dBNames }; 


//console.log(JSON.stringify(query, null, 2)); 

Programs.update({ _id: teacherid }, { $push: query }, callback); 
+0

我認爲你不能在這裏使用$,如果你想要把所有dbNames那麼你需要使用$每個而不是$在 –

+0

感謝您指出出$而不是$ in。我正在考慮美元拉運營商。您構建對象的方式給出了一個錯誤,聲稱它不能將$ push應用於非數組。我建立對象的方法沒有錯誤,但是我錯過了(而且你是對的),對象的值應該是{'$ each':dbNames}。 –