diff --git a/lib/mongodb.js b/lib/mongodb.js index f8a4c4d41..1fcb06ec3 100644 --- a/lib/mongodb.js +++ b/lib/mongodb.js @@ -1386,22 +1386,9 @@ MongoDB.prototype.all = function all(modelName, filter, options, callback) { if (filter.where) { query = self.buildWhere(modelName, filter.where, options); } - // Use Object.assign to avoid change filter.fields - // which will cause error when create model from data - let fields = undefined; - if (typeof filter.fields !== 'undefined') { - fields = []; - Object.assign(fields, filter.fields); - } - - // Convert custom column names - fields = self.fromPropertyToDatabaseNames(modelName, fields); options = buildOptions({}, options); - if (fields) { - options.projection = fieldsArrayToObj(fields); - } this.execute(modelName, 'find', query, options, processResponse); function processResponse(err, cursor) { @@ -1409,6 +1396,21 @@ MongoDB.prototype.all = function all(modelName, filter, options, callback) { return callback(err); } + // Use Object.assign to avoid change filter.fields + // which will cause error when create model from data + let fields = undefined; + if (typeof filter.fields !== 'undefined') { + fields = []; + Object.assign(fields, filter.fields); + } + + // Convert custom column names + fields = self.fromPropertyToDatabaseNames(modelName, fields); + + if (fields) { + cursor.project(fieldsArrayToObj(fields)); + } + const collation = options && options.collation; if (collation) { cursor.collation(collation); diff --git a/test/mongodb.test.js b/test/mongodb.test.js index 2ffb09f73..ac7783295 100644 --- a/test/mongodb.test.js +++ b/test/mongodb.test.js @@ -2379,6 +2379,36 @@ describe('mongodb connector', function() { }); }); + it('all return should honor filter.fields and not apply them to included relations', function(done) { + const user = new User({name: 'Matt'}); + user.save(function(err, user) { + const post = new Post({title: 'b', content: 'BBB', userId: user.id}); + post.save(function(err, post) { + db.connector.all( + 'Post', + {fields: ['title', 'userId'], where: {title: 'b'}, include: 'user'}, + {}, + function(err, posts) { + should.not.exist(err); + posts.should.have.lengthOf(1); + post = posts[0]; + post.should.have.property('title', 'b'); + should.not.exist(post.content); + should.not.exist(post._id); + should.not.exist(post.id); + post.should.have.property('userId'); + post.should.have.property('user'); + const {user} = post; + user.should.have.property('id'); + user.should.have.property('name', 'Matt'); + + done(); + }, + ); + }); + }); + }); + it('create should convert id from ObjectID to string', function(done) { const oid = new db.ObjectID(); const sid = oid.toString();