Skip to content

Commit

Permalink
Merge pull request #12341 from Automattic/vkarpov15/gh-12233
Browse files Browse the repository at this point in the history
fix(document): allow calling `$assertPopulated()` with values to better support manual population
  • Loading branch information
vkarpov15 committed Aug 30, 2022
2 parents 20584b2 + 1563a1b commit b60d0e6
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
21 changes: 15 additions & 6 deletions lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -4421,23 +4421,32 @@ Document.prototype.$populated = Document.prototype.populated;
* doc.$assertPopulated('author'); // does not throw
* doc.$assertPopulated('other path'); // throws an error
*
* // Manually populate and assert in one call. The following does
* // `doc.$set({ likes })` before asserting.
* doc.$assertPopulated('likes', { likes });
*
* @param {String|String[]} paths
*
* @param {String|String[]} path path or array of paths to check. `$assertPopulated` throws if any of the given paths is not populated.
* @param {Object} [values] optional values to `$set()`. Convenient if you want to manually populate a path and assert that the path was populated in 1 call.
* @return {Document} this
* @memberOf Document
* @method $assertPopulated
* @instance
* @api public
*/

Document.prototype.$assertPopulated = function $assertPopulated(paths) {
if (Array.isArray(paths)) {
paths.forEach(path => this.$assertPopulated(path));
Document.prototype.$assertPopulated = function $assertPopulated(path, values) {
if (Array.isArray(path)) {
path.forEach(p => this.$assertPopulated(p, values));
return this;
}

if (!this.$populated(paths)) {
throw new MongooseError(`Expected path "${paths}" to be populated`);
if (arguments.length > 1) {
this.$set(values);
}

if (!this.$populated(path)) {
throw new MongooseError(`Expected path "${path}" to be populated`);
}

return this;
Expand Down
2 changes: 1 addition & 1 deletion types/document.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ declare module 'mongoose' {
__v?: any;

/** Assert that a given path or paths is populated. Throws an error if not populated. */
$assertPopulated<Paths = {}>(paths: string | string[]): Omit<this, keyof Paths> & Paths;
$assertPopulated<Paths = {}>(path: string | string[], values?: Partial<Paths>): Omit<this, keyof Paths> & Paths;

/* Get all subdocs (by bfs) */
$getAllSubdocs(): Document[];
Expand Down

0 comments on commit b60d0e6

Please sign in to comment.