Skip to content

Commit

Permalink
Merge pull request #625 from jetstudio-io/master
Browse files Browse the repository at this point in the history
fix: allows to use filters with customized filed names
  • Loading branch information
agnes512 authored Mar 28, 2021
2 parents 0264cd8 + 8bdadd1 commit d26b439
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
21 changes: 18 additions & 3 deletions lib/mongodb.js
Original file line number Diff line number Diff line change
Expand Up @@ -1338,8 +1338,17 @@ MongoDB.prototype.convertColumnNames = function(model, data, direction) {
}

if (direction === 'database') {
data[columnName] = data[propName];
delete data[propName];
// Handle data is Array object - in case of fields filter
if (Array.isArray(data)) {
const idx = data.indexOf(propName);
if (idx !== -1) {
data.push(columnName);
delete data[idx];
}
} else { // Handle data as Object - in case to create / update
data[columnName] = data[propName];
delete data[propName];
}
}

if (direction === 'property') {
Expand Down Expand Up @@ -1377,7 +1386,13 @@ MongoDB.prototype.all = function all(modelName, filter, options, callback) {
if (filter.where) {
query = self.buildWhere(modelName, filter.where, options);
}
let fields = filter.fields;
// 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);
Expand Down
22 changes: 22 additions & 0 deletions test/mongodb.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2379,6 +2379,28 @@ describe('mongodb connector', function() {
});
});

it('should allow to use filters with customized field names', function(done) {
const post = new PostWithStringIdAndRenamedColumns({renamedTitle: 'b', renamedContent: 'BBB'});
post.save(function(err, post) {
db.connector.all(
'PostWithStringIdAndRenamedColumns',
{fields: ['renamedTitle', 'renamedContent']},
{},
function(err, posts) {
should.not.exist(err);
posts.should.have.lengthOf(1);
post = posts[0];
post.should.have.property('renamedTitle', 'b');
post.should.have.property('renamedContent', 'BBB');
should.not.exist(post.content);
should.not.exist(post._id);
should.not.exist(post.id);
done();
},
);
});
});

it('create should convert id from ObjectID to string', function(done) {
const oid = new db.ObjectID();
const sid = oid.toString();
Expand Down

0 comments on commit d26b439

Please sign in to comment.