2015-05-12 19 views
2

我在引用數組中引用了ID。當我試試這個:

Task.find({ game: req.user.game }).exec(function(err, task) { 
    if(err) { 
     console.log(err); 
    } else { 
     console.log(task[0].inCategories); 
    } 
}); 

它在引號node.js的控制檯(["5550a9604b24bcdc1b88cc76", "5551213c35d0516807b2cd99"])寫道ID數組。但後來我試圖返回任務的登錄用戶(看旁邊console.log命令註釋):

Profession.find({ _id: req.user.profession }).exec(function(err, profession) { 
    if(err) { 
     return res.status(400).send({ 
      message: errorHandler.getErrorMessage(err) 
     }); 
    } else { 
     console.log(profession[0].assignedTaskCategories); // output: array with quoted IDs 
     var pipeline = [ 
      { 
       '$match': { 'game': req.user.game, } 
      }, 
      { 
       '$project': { 
        'title': 1, 
        'game': 1, 
        'inCategories': 1, 
        'sameElements': { 
         '$setEquals': [ '$inCategories', profession[0].assignedTaskCategories ] 
        } 
       } 
      } 
     ]; 
     Task.aggregate(pipeline).exec(function (err, tasks){ 
      if(err) { 
       return res.status(400).send({ 
        message: errorHandler.getErrorMessage(err) 
       }); 
      } else { 
       console.log(tasks[0].inCategories); //array with IDs without quotes 
       res.json(tasks); 
      } 
     }); 
    } 
}); 

sameElements值是假的,因爲$setEquals比較陣列,一個帶引號的ID,一個沒有引號,我不知道它爲什麼發生?

回答

0

嘗試鑄造assignedTaskCategories要素的ObjectID第然後做比較:

console.log(profession[0].assignedTaskCategories); // output: array with quoted IDs 
var assignedTaskCategories = profession[0].assignedTaskCategories.map(function(category) { 
    return mongoose.Types.ObjectId(category); 
}); 
var pipeline = [ 
    { 
     '$match': { 'game': req.user.game, } 
    }, 
    { 
     '$project': { 
      'title': 1, 
      'game': 1, 
      'inCategories': 1, 
      'sameElements': { 
       '$setEquals': [ '$inCategories', assignedTaskCategories ] 
      } 
     } 
    } 
]; 
Task.aggregate(pipeline).exec(function (err, tasks){ 
    if(err) { 
     return res.status(400).send({ 
      message: errorHandler.getErrorMessage(err) 
     }); 
    } else { 
     console.log(tasks[0].inCategories); //array with IDs without quotes 
     console.log(tasks[0].sameElements); //true or false 
     res.json(tasks); 
    } 
}); 
+0

好了,現在兩個數組有沒有引號ID,但sameElements是假:('[55362abef762ff2422366854, 5550a9604b24bcdc1b88cc76, 5551213c35d0516807b2cd99] [5550a9604b24bcdc1b88cc76,5551213c35d0516807b2cd99]' – user3216673

+0

@ user3216673數組是否相同?您可以在應用聚合管道之前對兩個數組執行一些日誌記錄,並查看它們是否相等。 (http://docs.mongodb.org/manual/reference/operator/aggregation/setEquals/)com如果兩個或多個數組具有相同的獨特元素,則返回true,否則返回false。 – chridam

+0

@ user3216673這些都不一樣,這就是爲什麼它返回false; '[55362abef762ff2422366854,5550a9604b24bcdc1b88cc76,5551213c35d0516807b2cd99]'不等於'[5550a9604b24bcdc1b88cc76,5551213c35d0516807b2cd99]',因爲有一個額外的ID元素'55362abef762ff2422366854'不在另一個陣列中。 – chridam