Skip to content

Commit

Permalink
Merge pull request #7478 from chrischen/master
Browse files Browse the repository at this point in the history
Added dot sytnax support for alias queries.
  • Loading branch information
vkarpov15 authored Feb 3, 2019
2 parents ef2ab11 + 6032685 commit 899ccdd
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
27 changes: 22 additions & 5 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -1587,15 +1587,32 @@ Model.discriminators;
* @return {Object} the translated 'pure' fields/conditions
*/
Model.translateAliases = function translateAliases(fields) {
const aliases = this.schema.aliases;

if (typeof fields === 'object') {
// Fields is an object (query conditions or document fields)
for (const key in fields) {
if (aliases[key]) {
fields[aliases[key]] = fields[key];
delete fields[key];
let alias;
const translated = [];
const fieldKeys = key.split('.');
let currentSchema = this.schema;
for (const field in fieldKeys) {
const name = fieldKeys[field];
if (currentSchema && currentSchema.aliases[name]) {
alias = currentSchema.aliases[name];
// Alias found,
translated.push(alias);
} else {
// Alias not found, so treat as un-aliased key
translated.push(name);
}

// Check if aliased path is a schema
if (currentSchema.paths[alias])
currentSchema = currentSchema.paths[alias].schema;
else
currentSchema = null;
}
fields[translated.join('.')] = fields[key];
delete fields[key]; // We'll be using the translated key instead
}

return fields;
Expand Down
11 changes: 9 additions & 2 deletions test/model.translateAliases.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,12 @@ const mongoose = start.mongoose;

describe('model translate aliases', function() {
it('should translate correctly', function() {
const Syntax =new mongoose.Schema({
s: { type: String, alias: 'syntax' }
});

const Character = mongoose.model('Character', new mongoose.Schema({
d: { type: Syntax, alias: 'dot' },
name: { type: String, alias: '名' },
bio: {
age: { type: Number, alias: '年齢' }
Expand All @@ -22,12 +27,14 @@ describe('model translate aliases', function() {
// Translate aliases
Character.translateAliases({
'名': 'Stark',
'年齢': 30
'年齢': 30,
'dot.syntax': 'DotSyntax'
}),
// How translated aliases suppose to look like
{
name: 'Stark',
'bio.age': 30
'bio.age': 30,
'd.s': 'DotSyntax'
}
);
});
Expand Down

0 comments on commit 899ccdd

Please sign in to comment.