Skip to content

Commit

Permalink
Merge pull request #105 from Danchoys/master
Browse files Browse the repository at this point in the history
Add support for nested autopopulated virtuals
  • Loading branch information
vkarpov15 authored Dec 29, 2022
2 parents 7d39513 + f411f4b commit f9c112b
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 11 deletions.
19 changes: 8 additions & 11 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -171,17 +171,6 @@ function getPathsToPopulate(schema) {
}
});

if (schema.virtuals) {
Object.keys(schema.virtuals).forEach(function(pathname) {
if (schema.virtuals[pathname].options.autopopulate) {
pathsToPopulate.push({
options: defaultOptions(pathname, schema.virtuals[pathname].options),
autopopulate: schema.virtuals[pathname].options.autopopulate
});
}
});
}

return pathsToPopulate;
}

Expand Down Expand Up @@ -263,4 +252,12 @@ function eachPathRecursive(schema, handler, path) {
}
path.pop();
});

if (schema.virtuals) {
Object.keys(schema.virtuals).forEach(function(pathname) {
path.push(pathname);
handler(path.join('.'), schema.virtuals[pathname]);
path.pop();
});
}
}
41 changes: 41 additions & 0 deletions test/unit.js
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,47 @@ describe('mongoose-autopopulate:unit', function() {
assert.deepEqual(pathsToPopulate[0].path,
'nested.test');
});

it('handles top-level populated virtuals', () => {
schemaStub = createSchemaStub([]);
schemaStub.virtuals = {
test: {
options: { autopopulate: true }
}
};

plugin(schemaStub);
assert.equal(schemaStub.pre.calls.length, 3);

const pathsToPopulate = schemaStub.pre.calls[0].handler.call({});
assert.equal(pathsToPopulate.length, 1);
assert.equal(pathsToPopulate[0].path, 'test');
});

it('handles nested populated virtuals', () => {
const nestedSchema = createSchemaStub([]);
nestedSchema.virtuals = {
test: {
options: { autopopulate: true }
}
};

const topLevel = {
name: 'nested',
options: {
schema: nestedSchema
}
};

const schema = createSchemaStub([topLevel]);

plugin(schema);
assert.equal(schema.pre.calls.length, 3);

const pathsToPopulate = schema.pre.calls[0].handler.call({});
assert.equal(pathsToPopulate.length, 1);
assert.equal(pathsToPopulate[0].path, 'nested.test');
});
});

function createSchemaStub(paths) {
Expand Down

0 comments on commit f9c112b

Please sign in to comment.