Ben Drury
Ben Drury

Reputation: 1376

Issue finding mongoose ObjectID in array of strings representing ObjectIDs

I need to find the index of the mongoose objectID in an array like this:

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

The model I am using to compare is a mongoose schema with the following data:

{_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 }

I am trying to find the index of the model._user in the array above using the following:

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

Where individualScores is the original array and taskList[i] is the task model. However, this always returns -1. It never finds the correct _id in the array.

Upvotes: 0

Views: 832

Answers (2)

Shaishab Roy
Shaishab Roy

Reputation: 16805

I think your process should working well that you are using just only need to convert 'objectID' to String to compare. Convert using .toString() for both of _id and _user.

like bellow:

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

Upvotes: 0

Sam Quinn
Sam Quinn

Reputation: 3881

I guess your problem is related to how _id are returned by your query

If you get _id as String, your code should work, check the snippet below

But if instead, you get ObjectsIds, you have to cast them to String first

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)

Upvotes: 1

Related Questions