3

I have the following schema:

var daySchema = new Schema({
date: {
    type: Date,
    required: true
},
activities: [{
    type: Schema.Types.ObjectId,
    ref: 'Activity'
}]
});

And I am removing an activity within the daySchema:

var index = day.activities.indexOf("584aa9c16791eb1ec4ad8e73");
day.activities.splice(index, 1);

Can someone explain me why this works ?. The array "activities" is an array of "ObjectId". So the "indexOf" should not work with objects, but still the "indexOf" is able to find the element based on the id. This is driving me crazy, is something else going on here, maybe a map function inside ObjectId ?

FraK
  • 690
  • 10
  • 18

1 Answers1

6

This works because Mongoose wraps an array in MongooseArray which provides its own indexOf method which supports this string-based comparison rather than the strict equality test used by the native array implementation.

JohnnyHK
  • 270,398
  • 59
  • 567
  • 434
  • I didn't know about "MongooseArray", thank you very much for the info, this seems to be the reason ! – FraK Dec 09 '16 at 17:34
  • 1
    that `indexOf` link doesn't seem to redirect to the `indexOf` doc anymore so it's probably going to be difficult to know that `indexOf` has special semantics unfortunately – solstice333 Aug 17 '18 at 20:29