Regression in 3.8.17: toObject transform are now called in Model.save()
Up until mongoose 3.8.16 Schema.options.toObject.transform was not called in Model.save(), only by Model.toObject().
Since 3.8.17 (specifically since commit d098ad3820dca4f69691b2f3b62d9fc9cdec924a) the transform function is called in Model.save() and it breaks our code.
Indeed we use the transform function to hide internal data from the outside when calling Model.toObject() (the hidden data is only handled by Schema methods, so it should not leak outside of the model file).
With commit d098ad3820dca4f69691b2f3b62d9fc9cdec924a the transform function is somehow called when calling Model.create() (which calls Model.save()), and then the document inserted in MongoDB is all wrong.
Was the call to the transform function really wanted by commit d098ad3820dca4f69691b2f3b62d9fc9cdec924a ?
I am experiencing problems with Model.save() as well. Models created like
var newModel = new ModelName({...});
newModel.save();
are not even saving for me. It claims an _id does not exist. I'm thinking this is related.
I had the similar phenomenon, although I'm not sure which is expected.
I had some virtual getters and set virtuals option to true. Since I've upgrade mongoose to 3.8.17, my virtual values are stored in MongoDB when a object is newly created. This phenomenon was not occurred in 3.8.16.
...
FooSchema.virtual('fullName').get(function(){
return this.firstName + this.lastName;
});
FooSchema.set('toObject', {
virtuals: true
});
mongoose.model('Foo', FooSchema);
Foo.create({
firstName: 'Yutaka',
lastName: 'Yamaguchi'
})
- 3.8.16 stored firstName and lastName, and not stored fullName in MongoDB
- 3.8.17 stored firstName and lastName, and also stored fullName in MongoDB
@cquartier yes it's related, in fact this is the error we get, because our transform function removes _id. If I remember correctly there is a feature in mongoose to automatically replace _id by id and this may be why you have this issue, even if you don't define a transform function.
So I think that the fix in commit d098ad3820dca4f69691b2f3b62d9fc9cdec924a should in fact have introduced new options: for internal usage only (in save), and not re-use the public toObject options. This will still fix the fields ordering issue as well as not introduce the current regression.
Yeah that was my bad, I'm sorry guys. This bug leaked in when I made it possible to retain key order when saving a document. This was also opened in #2340, and fixed by @chetverikov in https://github.com/LearnBoost/mongoose/commit/9b6e419a2ef722b631435c5cff36167352d5d7f3 . The fix will be in 3.8.18.