0

If Mongoose models are designed to work with the instance, and statics are to work with the schema, then why / how does a static method provide access to the document object?

Example:

The following code allows me to convert from a Mongoose document to a JSON document:

appSchema.statics.toItem = function (done) {
    var item = toItemSync(this);
    return done(null, item);
};

function toItemSync (model) {
    return {
        id : model.id,
        [snip]
    };
}

var App = mongoose.model('App', appSchema);

module.exports = App;

I'm calling the toItem() from my routes to strip off info from the document that should not be sent to the client...

models.Application.findById(id, function(err, app) {
    if (err) { return next(err); }
    if (!app) { return next('Invalid ID'); }

    app.toItem(function(err, appItem){
        if (err) { return next(err); }
        res.send(appItem);
    });
});

All of the docs I'm reading lead me to believe this is not (or should not) be possible:

What is the difference between methods and statics in Mongoose?

Community
  • 1
  • 1
G. Deward
  • 1,542
  • 3
  • 17
  • 30
  • Can you show an example of how you use `toItem()`? – robertklep Aug 02 '16 at 18:45
  • Sure. I've edited the question to show how I'm using it. – G. Deward Aug 02 '16 at 19:12
  • Similar code throws an error for me (_"app.toItem is not a function"_), as expected. I'm testing with `mongoose@4.5.8`. – robertklep Aug 02 '16 at 19:51
  • Interesting. It's a common pattern I've been using everywhere for the past year or so. The functions are setup, as shown, before the model is created. I'm currently on v4.5.5. – G. Deward Aug 02 '16 at 20:27
  • I've created a gist with the code I tested with ([here](https://gist.github.com/robertklep/7d4c1f95939826b341daf95b69b647ee)). I explicitly tested it with 4.5.5, which fails with the same error as I mentioned before. – robertklep Aug 02 '16 at 20:40

0 Answers0