MongooseArrayのindexOf
node.jsいじってます。
さらっと備忘録
mongoose.Schema.Types.ObjectId
ObjectIdの比較は===ではダメ、anObjectId.equals(anotherObjectId)を使う
Array.indexOf(obj)
// mongooseのモデル var FooSchema = new Schema( {bars: [{type: ObjectId, ref: hoge}])}
Array.indexOf(obj)での比較は===でやってる
underscore.jsの_.contains(array, obj)もそう。
// barsの中にanBarが含まれているとする。 // ObjectIdを===で比較するとうまくいかないはずだが・・・ foo.bars.indexOf(anBar) != -1 // なぜかfalseになる(つまり、含まれているという正しい結果を返す)
うまく行かないはずなのになぜかうまく行く、最も怖いパターンなので調査開始
for文で回して===で比較するとやはり普通にダメ、なぜかindexOfだと行ける
mongooseで、配列と思わしきものは実はMongooseArrayだった罠
http://mongoosejs.com/docs/api.html#types_array_MongooseArray-indexOf
MongooseArrayでindexOfするとObjectIdはequalsで比較してくれるようだ。
なお、上にも書いたように_.contains使うと===の比較だから代用出来ない。
ううん・・・
ちょっとびっくりした
populate("bars")した後とかだと、ObjectIdの配列(MongooseArray)じゃなくてObject自体の配列(Array)になってしまってるので(多分)
// CoffeeScriptの文法で失礼 (_.find bars, (bar)-> bar._id.equals(anBar._id))?
とするのがよさそう。