Skip to content

Commit b60d0e6

Browse files
authored
Merge pull request #12341 from Automattic/vkarpov15/gh-12233
fix(document): allow calling `$assertPopulated()` with values to better support manual population
2 parents 20584b2 + 1563a1b commit b60d0e6

File tree

2 files changed

+16
-7
lines changed

2 files changed

+16
-7
lines changed

lib/document.js

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4421,23 +4421,32 @@ Document.prototype.$populated = Document.prototype.populated;
44214421
* doc.$assertPopulated('author'); // does not throw
44224422
* doc.$assertPopulated('other path'); // throws an error
44234423
*
4424+
* // Manually populate and assert in one call. The following does
4425+
* // `doc.$set({ likes })` before asserting.
4426+
* doc.$assertPopulated('likes', { likes });
44244427
*
4425-
* @param {String|String[]} paths
4428+
*
4429+
* @param {String|String[]} path path or array of paths to check. `$assertPopulated` throws if any of the given paths is not populated.
4430+
* @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.
44264431
* @return {Document} this
44274432
* @memberOf Document
44284433
* @method $assertPopulated
44294434
* @instance
44304435
* @api public
44314436
*/
44324437

4433-
Document.prototype.$assertPopulated = function $assertPopulated(paths) {
4434-
if (Array.isArray(paths)) {
4435-
paths.forEach(path => this.$assertPopulated(path));
4438+
Document.prototype.$assertPopulated = function $assertPopulated(path, values) {
4439+
if (Array.isArray(path)) {
4440+
path.forEach(p => this.$assertPopulated(p, values));
44364441
return this;
44374442
}
44384443

4439-
if (!this.$populated(paths)) {
4440-
throw new MongooseError(`Expected path "${paths}" to be populated`);
4444+
if (arguments.length > 1) {
4445+
this.$set(values);
4446+
}
4447+
4448+
if (!this.$populated(path)) {
4449+
throw new MongooseError(`Expected path "${path}" to be populated`);
44414450
}
44424451

44434452
return this;

types/document.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ declare module 'mongoose' {
2626
__v?: any;
2727

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

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

0 commit comments

Comments
 (0)