2

I have added a transform function to my Schema's toObject to strip certain properties, and change the name of _id to id. It works great when I use findOne and call toObject on the result, but I also have a find({}, (err, items) => {...}) command. There's no way to call toObject on the array.

Here's my schema:

var ItemSchema = new Schema({
    version: {type: String, default: '1.0.0'},
    created: {type: Date, default: Date.now},
    modified: {type: Date, default: Date.now},
    properties: Schema.Types.Mixed
  }, {
  toObject: {
    transform: (doc, ret) => {
      // remove the _id and __v of every document before returning the result
      ret.id = doc.id;
      delete ret._id;
      delete ret.__v;
    }
  }
});

I've looked it up, and could only find this question, where the recommended answer is to use lean() - which does not help me.

As a workaround, I added the line var result = items.map(x => x.toObject());, and while it works great, I wonder if there's a way to trigger the transform automatically on any document returned - single or array, so I won't have to iterate over the results.

2
  • 1
    as I understand it, you shouldnt have to call toObject manually if you have added the correct options to the schema. could you provide code for how you added the transformation to toObject? I suspect the key is there Commented May 25, 2015 at 4:45
  • @rompetroll added schema code. Cheers! Commented May 25, 2015 at 6:58

2 Answers 2

1

I’ve created a mongoose plugin to do things like that.

 var cleanup = function (schema) {
     var toJSON = schema.methods.toJSON || mongoose.Document.prototype.toJSON;

     schema.set('toJSON', {
         virtuals: true
     });

     schema.methods.toJSON = function () {
         var json = toJSON.apply(this, arguments);

         delete json._id;
         delete json.__t;
         delete json.__v;

         return json;
     };
 };

Basically, it overrides toJSON (though you can do the same with toObject).

By the way, there’s already an id virtual property, defined by mongoose (unless you set id to false in the schema options).

I use it as such:

ItemSchema.plugin(cleanup);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Bertrand, I understand I can do this with plugins, but I was wondering if I can just use the transform function - I thought that was its purpose.
0

Well, after looking around for a while, I finally settled on converting the results to objects myself. As mentioned in the question, instead of: return items; I have return items.map(x => x.toObject());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.