Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(document): allow calling $assertPopulated() with values to better support manual population #12341

Merged
merged 2 commits into from
Aug 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 15 additions & 6 deletions lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -4417,23 +4417,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