在表示对象 ID 的字符串数组中查找猫鼬对象 ID 时出现问题



我需要在这样的数组中找到猫鼬对象ID的索引:

[ { _id: 58676b0a27b3782b92066ab6, score: 0 },
{ _id: 58676aca27b3782b92066ab4, score: 3 },
{ _id: 58676aef27b3782b92066ab5, score: 0 }]

我用来比较的模型是具有以下数据的猫鼬模式:

{_id: 5868d41d27b3782b92066ac5,
updatedAt: 2017-01-01T21:38:30.070Z,
createdAt: 2017-01-01T10:04:13.413Z,
recurrence: 'once only',
end: 2017-01-02T00:00:00.000Z,
title: 'Go to bed without fuss / coming down',
_user: 58676aca27b3782b92066ab4,
__v: 0,
includeInCalc: true,
result: { money: 0, points: 4 },
active: false,
pocketmoney: 0,
goals: [],
pointsawarded: { poorly: 2, ok: 3, well: 4 },
blankUser: false }

我正在尝试使用以下方法在上面的数组中找到model._user的索引:

var isIndex = individualScores.map(function(is) {return is._id; }).indexOf(taskList[i]._user);

其中 individualScore 是原始数组,taskList[i] 是任务模型。 但是,这始终返回 -1。 它永远不会在数组中找到正确的_id。

我想您的问题与您的查询如何返回_id有关

如果您_idString,您的代码应该可以工作,请检查下面的代码片段

但是,如果相反,你得到ObjectsIds,你必须首先将它们转换为字符串

var individualScores = [
{ _id: "58676b0a27b3782b92066ab6", score: 0 },
{ _id: "58676aca27b3782b92066ab4", score: 3 },
{ _id: "58676aef27b3782b92066ab5", score: 0 }
]
var task = { 
_id: "5868d41d27b3782b92066ac5",
updatedAt: new Date("2017-01-01T21:38:30.070Z"),
createdAt: new Date("2017-01-01T10:04:13.413Z"),
recurrence: 'once only',
end: new Date("2017-01-02T00:00:00.000Z"),
title: 'Go to bed without fuss / coming down',
_user: "58676aca27b3782b92066ab4",
__v: 0,
includeInCalc: true,
result: { money: 0, points: 4 },
active: false,
pocketmoney: 0,
goals: [],
pointsawarded: { poorly: 2, ok: 3, well: 4 },
blankUser: false
}
var isIndex = individualScores.map(
function(is) {
return is._id; 
})
.indexOf(task._user);
console.log(isIndex)

我认为您的过程应该运行良好,您只需要将"objectID"转换为String即可进行比较。使用.toString()进行转换 对于_id_user

像波纹管:

var isIndex = individualScores.map(function(is) {
return is._id.toString(); 
}).indexOf(taskList[i]._user.toString());

最新更新