Mongoose: Getter not working on find

Created on 19 Jun 2014  路  4Comments  路  Source: Automattic/mongoose

Why getters aren't being called with modelName.find(callback)? FindOne() and other similar functions seems to be calling getters just fine, but with find the getters of schema types are not working. I've seen this problem being reported on stackoverflow and other forums, but I was unable to find an appropriate answer/solution.

So far, I was able to bypass the problem by iterating over the docs returned by find and calling doc.toObject({getters: true}) on each one, but this seems rather inefficient. Is there a better solution?

can't reproduce

Most helpful comment

maybe you just forgot to configure your schema (like me):

mySchema = new Schema( {}, {
    toObject : {getters: true},
    toJSON : {getters: true}
});

All 4 comments

maybe you just forgot to configure your schema (like me):

mySchema = new Schema( {}, {
    toObject : {getters: true},
    toJSON : {getters: true}
});

Hmm @Tinadim is this only happening when you call toObject()? Can you provide some code that duplicates this?

@vkarpov15 no. As I said, the getters aren't being called when I use modeName.find(callbackName(error, docs){ }). Any other functions that return just one doc, like findOne, findById, etc, call the getters. In order to use apply the getters to the documents returned by find, I have to do something like this:

modelName.find(function(err, docs) {
for(var i in docs)
docs[i].toObject({getters : true});
});

Can you provide code that duplicates this and clarify which version of mongoose you're using? The below code seems to work against 3.8.15 just fine:

      var s = new Schema({
        food: { type: String, get: function(v) { return v.toLowerCase(); } }
      });

      var M = db.model('gh-2152', s, 'gh-2152');
      M.create({ food: 'Eggs' }, { food: 'Bacon' }, function(error) {
        assert.ifError(error);
        M.find({}, function(error, docs) {
          assert.ifError(error);
          assert.equal('eggs', docs[0].food);
          done();
        });
      });
Was this page helpful?
0 / 5 - 0 ratings

Related issues

ghost picture ghost  路  3Comments

simonxca picture simonxca  路  3Comments

adamreisnz picture adamreisnz  路  3Comments

varunjayaraman picture varunjayaraman  路  3Comments

jeneser picture jeneser  路  3Comments