Reputation: 2673
I am trying to write a plugin that should return extra data by setting on a field tags
already saved to model instead of saving set data on tags
to database and return.
Here is plugin code.
module.exports = function samTagsPlugin(schema, options) {
schema.post('init', function () {
document.set('tags', ['a', 'b', 'c']);
});
};
But, the tags
field is saved to mongodb with the values ['a', 'b', 'c']
. Is there any way I can just assign dynamic value to tags
and mongoose do not save the provided value to database?
Mongoose version I am using is 3.8.x
.
Upvotes: 1
Views: 456
Reputation: 2673
So here is how I solved this using virtual
fields (Thanks @Manu).
var MySchema = new Schema({
type: {
type: String,
uiGrid: {name: 'Type', order: 15},
required: true
},
contactNumber: {type: String, uiForm: {name: 'Contact Number'}},
__customTags: [String]
}, {
toObject: {
virtuals: true
},
toJSON: {
virtuals: true
}
});
Not that here I have added a field __customTags
. In mongoose everything starts with __
will not be persisted to database.
And then
MySchema.virtual('tags').get(function() {
return this.__customTags;
}).set(function(tags) {
this.__customTags = tags;
});
From my plugin, I am assigning tags
to an array of values I want.
this.set('tags', tags);
Upvotes: 0