Skip to content

Commit

Permalink
fix(document): allow calling $assertPopulated() with values to bett…
Browse files Browse the repository at this point in the history
…er support manual population

Fix #12233
  • Loading branch information
vkarpov15 committed Aug 27, 2022
1 parent 76201d0 commit d87e627
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
16 changes: 10 additions & 6 deletions lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -4418,22 +4418,26 @@ Document.prototype.$populated = Document.prototype.populated;
* doc.$assertPopulated('other path'); // throws an error
*
*
* @param {String|String[]} paths
* @param {String|String[]} path
* @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 d87e627

Please sign in to comment.