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?
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();
});
});
Most helpful comment
maybe you just forgot to configure your schema (like me):