Pass query parameters to mongoose schema's toJSON method

200 views
Skip to first unread message

Taavi Juursalu

unread,
Apr 14, 2017, 8:19:24 AM4/14/17
to Mongoose Node.JS ODM

i am making a plugin and have a question how to solve a problem: I have Mixed subschema that has a plugin attached:

{ title: translateableSchema, otherStuff: String }

translateableSchema is basically the following: { "en": "Title", "de": "Titel"}. The catch is that the language keys are dynamic defined by the users. So I can not use predefined options.

Also I want filter out other translations the following ways:

Post.find({}).translate("en").exec(function(err, posts){

});

The schema currently uses the toJSON transform function to remove other translations but I have a problem how to pass the "en" parameter to the function without calling it manually on all returned documents.

I tried setting it as a schema option but this persists to other query calls that to not have the translate("en") query function attached. So I cant return all the translations in cases when I need to show the users all the translations.

Here is my code

var mongoose = require('mongoose');

function _plugin(schema, options) {
    schema.pre("validate", function(next, data) { //Check the input and populate default values
    if (this.isNew) {
        delete data.en;
        this.set("es", "Hola");
    }
    next();
  });

  mongoose.Query.prototype["translate"] = function(lang) {
    schema.statics.translate(lang);
    return this;
  } 
}

var _schema = new mongoose.Schema({

}, {
  strict: false,
  toJSON: {
    transform: function(doc, ret) {
        delete ret._id;

        //Delete here other unneeded stuff
      }
  }
});

_schema.plugin(_plugin, { language: false });

module.exports = exports = _schema;

http://stackoverflow.com/questions/43375960/pass-dynamic-parameters-to-mongoose-schemas-tojson-method
Reply all
Reply to author
Forward
0 new messages