Skip to content

Commit db63a31

Browse files
GonyodaJanny
authored and
Janny
committedJun 5, 2018
Fields projection fix (#436)
* mongodb find, use fields in projection * eliminate unnecessary calls during data map * update filter.fields unit test to avoid juggler
1 parent 3116da3 commit db63a31

File tree

2 files changed

+11
-5
lines changed

2 files changed

+11
-5
lines changed
 

‎lib/mongodb.js

+9-3
Original file line numberDiff line numberDiff line change
@@ -1106,7 +1106,9 @@ MongoDB.prototype.all = function all(model, filter, options, callback) {
11061106
fields = self.fromPropertyToDatabaseNames(model, fields);
11071107

11081108
if (fields) {
1109-
this.execute(model, 'find', query, fields, processResponse);
1109+
// convert the array of fields into a projection object see http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#find
1110+
var findOpts = { projection: fields };
1111+
this.execute(model, 'find', query, findOpts, processResponse);
11101112
} else {
11111113
this.execute(model, 'find', query, processResponse);
11121114
}
@@ -1130,6 +1132,10 @@ MongoDB.prototype.all = function all(model, filter, options, callback) {
11301132
} else if (filter.offset) {
11311133
cursor.skip(filter.offset);
11321134
}
1135+
1136+
var shouldSetIdValue = idIncluded(fields, idName);
1137+
var deleteMongoId = fields || idName !== '_id';
1138+
11331139
cursor.toArray(function(err, data) {
11341140
if (self.debug) {
11351141
debug('all', model, filter, err, data);
@@ -1138,11 +1144,11 @@ MongoDB.prototype.all = function all(model, filter, options, callback) {
11381144
return callback(err);
11391145
}
11401146
var objs = data.map(function(o) {
1141-
if (idIncluded(fields, self.idName(model))) {
1147+
if (shouldSetIdValue) {
11421148
self.setIdValue(model, o, o._id);
11431149
}
11441150
// Don't pass back _id if the fields is set
1145-
if (fields || idName !== '_id') {
1151+
if (deleteMongoId) {
11461152
delete o._id;
11471153
}
11481154

‎test/mongodb.test.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -1597,12 +1597,12 @@ describe('mongodb connector', function() {
15971597
it('all return should honor filter.fields', function(done) {
15981598
var post = new Post({ title: 'b', content: 'BBB' });
15991599
post.save(function(err, post) {
1600-
Post.all({ fields: ['title'], where: { title: 'b' }}, function(err, posts) {
1600+
db.connector.all('Post', { fields: ['title'], where: { title: 'b' }}, {}, function(err, posts) {
16011601
should.not.exist(err);
16021602
posts.should.have.lengthOf(1);
16031603
post = posts[0];
16041604
post.should.have.property('title', 'b');
1605-
post.should.have.property('content', undefined);
1605+
should.not.exist(post.content);
16061606
should.not.exist(post._id);
16071607
should.not.exist(post.id);
16081608

0 commit comments

Comments
 (0)
Please sign in to comment.