使用MongoDB $ setEquals时引用的ID

我在引用数组中引用的ID有问题。 当我尝试这个:

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

它将引号中的ID数组写入node.js console( ["5550a9604b24bcdc1b88cc76", "5551213c35d0516807b2cd99"] )。 但是然后我试图返回一个login用户的任务(查看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,一个没有引号,我不知道为什么会发生?

尝试先将assignedTaskCategories元素转换为ObjectIds,然后进行比较:

 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); } });