Can mongodb getter/setter methods access the document?

Viewed 1153

Can getter setter methods in Mongoose access attributes of the document itself? For instance could their behavior depend on whether the content is supposed to be compressed or not. Here I'm just making up this guessing that it might be bound to the document, but I can't readily see docs to this effect:

function compress(val) {
     if (this.compressed) return zlib.gzipSync(val);
     else return val;
}
function expand(val) {
     if (this.compressed) return zlib.gunzipSync(val);
     else return val;
}

var MyObject = new mongoose.Schema({
  content: {type: mongoose.Schema.Types.Mixed, set: compress, get: expand},
  compressed: {type: Boolean, required: true, default: false}

});

https://mongoosejs.com/docs/2.7.x/docs/getters-setters.html

1 Answers

Mongoose getters/setters documentation

The link you posted is from version 2.7 of Mongoose, which was released in 2012. The equivalent page in the new documentation answers most of your questions.

The rest can be answered by consulting the MDN documentation for getters and setters. The Mongoose schema getters and setters operate just like the Javascript ones (except for one thing, see note).

Specifics

this is indeed bound to the document.

Getters, however, don't accept a value. Your code should probably look like this

function compress(val) {
     if (this.compressed) return zlib.gzipSync(val);
     else return val;
}
function expand() {
     if (this.compressed) return zlib.gunzipSync(this.content);
     else return this.content;
}

var MyObject = new mongoose.Schema({
  content: {type: mongoose.Schema.Types.Mixed, set: compress, get: expand},
  compressed: {type: Boolean, required: true, default: false}
});
Related