[Mongoose] Schema.Types.Mixed だと save 前に .markModified が必要

Thu, February 28, 2013 - 1 min read

Node.js + Mongoose でインスタンスを save で保存できないときの原因のひとつに Schema.Types.Mixed があります。

プロパティの型が Schema.Types.Mixed とかだと、値に変更があったことを Mongoose が自動検知してくれないみたいです。

mongoose | マングース

To "tell" Mongoose that the value of a Mixed type has changed, call the .markModified(path) method of the document passing the path to the Mixed type you just changed.

[引用元]:Mongoose SchemaTypes v3.5.6

markModified メソッドの使い方は下記のような感じです。

var schema = new Schema({
  mixed:   Schema.Types.Mixed
})

// example use

var Thing = mongoose.model('Thing', schema);

var m = new Thing;
m.mixed = {[ any: { thing: 'i want' } ]};
m.markModified('mixed');
m.save(callback);

以上、Mongoose の Schema.Types.Mixed を使いこなしたい現場からお送りしました。