This is a reopen of #5497 (as I couldn't get a response there).
Reproduction was on Mongoose v4.11.7
Calling findOneAndUpdate
and updating a binary field saves the binary data incorrectly.
As mentioned in #5497 this is a breaking change that apparently introduced in version 4.11.2 (I suspect this commit: 1613ef5).
Please see the reproduction script below (which include runSettersOnQuery: true
):
var mongoose = require('mongoose'),
uuid = require('uuid'),
uuidParse = require('uuid-parse');
mongoose.Promise = Promise;
function generateUUID() {
var buffer = uuid.v4(null, new Buffer(16));
return new mongoose.Types.Buffer(buffer).toObject(0x04);
}
function toUUID(string) {
if (!string) {return null;}
if (Buffer.isBuffer(string) || Buffer.isBuffer(string.buffer)) { return string; }
var buffer = uuidParse.parse(string);
return new mongoose.Types.Buffer(buffer).toObject(0x04);
}
function fromUUID(buffer) {
if (!buffer || buffer.length !== 16) {return null;}
return uuidParse.unparse(buffer);
}
var UserSchema = new mongoose.Schema({
name: String,
foo: {
type: mongoose.Schema.Types.Buffer,
get: fromUUID,
set: toUUID
}
}, {collection: 'users'});
var UserModel = mongoose.model('User', UserSchema);
var connStr = 'mongodb://test:[email protected]/test';
mongoose.connect(connStr);
var user = {name: 'insert', foo: uuid.v4()};
console.log('Inserting user, my foo will be OK:', user);
var dalUser = new UserModel(user);
dalUser.save().then(() => {
console.log('User inserted successfully');
}).catch(console.error);
user = {name: 'upsert', foo: uuid.v4()};
console.log('Upserting user, my foo will be wrong:', user);
var opts = {upsert: true, setDefaultsOnInsert: true, runSettersOnQuery: true };
UserModel.findOneAndUpdate({foo: user.foo}, user, opts).exec().then(() => {
console.log('User upserted successfully');
}).catch(console.error);
And the result in the DB is:
Thanks!
Will double check why this changed, thanks for your patience.
Thanks for your patience @ValYouW and thanks for the very detailed bug report. We didn't notice it because the mongoose logs showed that we were saving with sub_type = 4
, but underneath the logs it ended up becoming sub_type = 0
. Fix will be in 4.11.9 tomorrow :+1: :beers:
Most helpful comment
Thanks for your patience @ValYouW and thanks for the very detailed bug report. We didn't notice it because the mongoose logs showed that we were saving with
sub_type = 4
, but underneath the logs it ended up becomingsub_type = 0
. Fix will be in 4.11.9 tomorrow :+1: :beers: