All files / src/operations update.ts

95.4% Statements 83/87
95.19% Branches 99/104
100% Functions 13/13
100% Lines 76/76

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313    408x         408x 408x 408x                                                                                                                 408x                 78053x 78053x 78053x   78053x       82575x       54914x 2040x     62454x               80743x 80743x 80743x           80743x 796x     80743x 1284x         80743x 1642x     80743x 80743x 3442x   216x       80527x 67814x         408x   26740x           26282x 731x                 27518x 20741x 19596x 19596x   19367x                       408x   17031x           17031x 229x                 16573x 15714x 14569x 14569x   14141x                                                   408x             9870x           9870x 458x                 11069x 8139x 8139x 8139x   8081x                     408x         214291x 229x     214062x 229x     213833x 213833x 16905x     213833x 26061x     213833x 3501x     213833x 3668x     213833x 2298x     213833x     408x 408x           408x         408x          
import type { Document } from '../bson';
import type { Collection } from '../collection';
import { MongoCompatibilityError, MongoInvalidArgumentError, MongoServerError } from '../error';
import type { InferIdType, TODO_NODE_3286 } from '../mongo_types';
import type { Server } from '../sdam/server';
import type { ClientSession } from '../sessions';
import { type TimeoutContext } from '../timeout';
import { hasAtomicOperators, type MongoDBNamespace } from '../utils';
import { type CollationOptions, CommandOperation, type CommandOperationOptions } from './command';
import { Aspect, defineAspects, type Hint } from './operation';
 
/** @public */
export interface UpdateOptions extends CommandOperationOptions {
  /** A set of filters specifying to which array elements an update should apply */
  arrayFilters?: Document[];
  /** If true, allows the write to opt-out of document level validation */
  bypassDocumentValidation?: boolean;
  /** Specifies a collation */
  collation?: CollationOptions;
  /** Specify that the update query should only consider plans using the hinted index */
  hint?: Hint;
  /** When true, creates a new document if no document matches the query */
  upsert?: boolean;
  /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
  let?: Document;
}
 
/**
 * @public
 * `TSchema` is the schema of the collection
 */
export interface UpdateResult<TSchema extends Document = Document> {
  /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */
  acknowledged: boolean;
  /** The number of documents that matched the filter */
  matchedCount: number;
  /** The number of documents that were modified */
  modifiedCount: number;
  /** The number of documents that were upserted */
  upsertedCount: number;
  /** The identifier of the inserted document if an upsert took place */
  upsertedId: InferIdType<TSchema> | null;
}
 
/** @public */
export interface UpdateStatement {
  /** The query that matches documents to update. */
  q: Document;
  /** The modifications to apply. */
  u: Document | Document[];
  /**  If true, perform an insert if no documents match the query. */
  upsert?: boolean;
  /** If true, updates all documents that meet the query criteria. */
  multi?: boolean;
  /** Specifies the collation to use for the operation. */
  collation?: CollationOptions;
  /** An array of filter documents that determines which array elements to modify for an update operation on an array field. */
  arrayFilters?: Document[];
  /** A document or string that specifies the index to use to support the query predicate. */
  hint?: Hint;
}
 
/**
 * @internal
 * UpdateOperation is used in bulk write, while UpdateOneOperation and UpdateManyOperation are only used in the collections API
 */
export class UpdateOperation extends CommandOperation<Document> {
  override options: UpdateOptions & { ordered?: boolean };
  statements: UpdateStatement[];
 
  constructor(
    ns: MongoDBNamespace,
    statements: UpdateStatement[],
    options: UpdateOptions & { ordered?: boolean }
  ) {
    super(undefined, options);
    this.options = options;
    this.ns = ns;
 
    this.statements = statements;
  }
 
  override get commandName() {
    return 'update' as const;
  }
 
  override get canRetryWrite(): boolean {
    if (super.canRetryWrite === false) {
      return false;
    }
 
    return this.statements.every(op => op.multi == null || op.multi === false);
  }
 
  override async execute(
    server: Server,
    session: ClientSession | undefined,
    timeoutContext: TimeoutContext
  ): Promise<Document> {
    const options = this.options ?? {};
    const ordered = typeof options.ordered === 'boolean' ? options.ordered : true;
    const command: Document = {
      update: this.ns.collection,
      updates: this.statements,
      ordered
    };
 
    if (typeof options.bypassDocumentValidation === 'boolean') {
      command.bypassDocumentValidation = options.bypassDocumentValidation;
    }
 
    if (options.let) {
      command.let = options.let;
    }
 
    // we check for undefined specifically here to allow falsy values
    // eslint-disable-next-line no-restricted-syntax
    if (options.comment !== undefined) {
      command.comment = options.comment;
    }
 
    const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0;
    if (unacknowledgedWrite) {
      if (this.statements.find((o: Document) => o.hint)) {
        // TODO(NODE-3541): fix error for hint with unacknowledged writes
        throw new MongoCompatibilityError(`hint is not supported with unacknowledged writes`);
      }
    }
 
    const res = await super.executeCommand(server, session, command, timeoutContext);
    return res;
  }
}
 
/** @internal */
export class UpdateOneOperation extends UpdateOperation {
  constructor(collection: Collection, filter: Document, update: Document, options: UpdateOptions) {
    super(
      collection.s.namespace,
      [makeUpdateStatement(filter, update, { ...options, multi: false })],
      options
    );
 
    if (!hasAtomicOperators(update)) {
      throw new MongoInvalidArgumentError('Update document requires atomic operators');
    }
  }
 
  override async execute(
    server: Server,
    session: ClientSession | undefined,
    timeoutContext: TimeoutContext
  ): Promise<UpdateResult> {
    const res: TODO_NODE_3286 = await super.execute(server, session, timeoutContext);
    if (this.explain != null) return res;
    Iif (res.code) throw new MongoServerError(res);
    if (res.writeErrors) throw new MongoServerError(res.writeErrors[0]);
 
    return {
      acknowledged: this.writeConcern?.w !== 0,
      modifiedCount: res.nModified ?? res.n,
      upsertedId:
        Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null,
      upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0,
      matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n
    };
  }
}
 
/** @internal */
export class UpdateManyOperation extends UpdateOperation {
  constructor(collection: Collection, filter: Document, update: Document, options: UpdateOptions) {
    super(
      collection.s.namespace,
      [makeUpdateStatement(filter, update, { ...options, multi: true })],
      options
    );
 
    if (!hasAtomicOperators(update)) {
      throw new MongoInvalidArgumentError('Update document requires atomic operators');
    }
  }
 
  override async execute(
    server: Server,
    session: ClientSession | undefined,
    timeoutContext: TimeoutContext
  ): Promise<UpdateResult> {
    const res: TODO_NODE_3286 = await super.execute(server, session, timeoutContext);
    if (this.explain != null) return res;
    Iif (res.code) throw new MongoServerError(res);
    if (res.writeErrors) throw new MongoServerError(res.writeErrors[0]);
 
    return {
      acknowledged: this.writeConcern?.w !== 0,
      modifiedCount: res.nModified ?? res.n,
      upsertedId:
        Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null,
      upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0,
      matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n
    };
  }
}
 
/** @public */
export interface ReplaceOptions extends CommandOperationOptions {
  /** If true, allows the write to opt-out of document level validation */
  bypassDocumentValidation?: boolean;
  /** Specifies a collation */
  collation?: CollationOptions;
  /** Specify that the update query should only consider plans using the hinted index */
  hint?: string | Document;
  /** When true, creates a new document if no document matches the query */
  upsert?: boolean;
  /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
  let?: Document;
}
 
/** @internal */
export class ReplaceOneOperation extends UpdateOperation {
  constructor(
    collection: Collection,
    filter: Document,
    replacement: Document,
    options: ReplaceOptions
  ) {
    super(
      collection.s.namespace,
      [makeUpdateStatement(filter, replacement, { ...options, multi: false })],
      options
    );
 
    if (hasAtomicOperators(replacement)) {
      throw new MongoInvalidArgumentError('Replacement document must not contain atomic operators');
    }
  }
 
  override async execute(
    server: Server,
    session: ClientSession | undefined,
    timeoutContext: TimeoutContext
  ): Promise<UpdateResult> {
    const res: TODO_NODE_3286 = await super.execute(server, session, timeoutContext);
    Iif (this.explain != null) return res;
    Iif (res.code) throw new MongoServerError(res);
    if (res.writeErrors) throw new MongoServerError(res.writeErrors[0]);
 
    return {
      acknowledged: this.writeConcern?.w !== 0,
      modifiedCount: res.nModified ?? res.n,
      upsertedId:
        Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null,
      upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0,
      matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n
    };
  }
}
 
export function makeUpdateStatement(
  filter: Document,
  update: Document | Document[],
  options: UpdateOptions & { multi?: boolean }
): UpdateStatement {
  if (filter == null || typeof filter !== 'object') {
    throw new MongoInvalidArgumentError('Selector must be a valid JavaScript object');
  }
 
  if (update == null || typeof update !== 'object') {
    throw new MongoInvalidArgumentError('Document must be a valid JavaScript object');
  }
 
  const op: UpdateStatement = { q: filter, u: update };
  if (typeof options.upsert === 'boolean') {
    op.upsert = options.upsert;
  }
 
  if (options.multi) {
    op.multi = options.multi;
  }
 
  if (options.hint) {
    op.hint = options.hint;
  }
 
  if (options.arrayFilters) {
    op.arrayFilters = options.arrayFilters;
  }
 
  if (options.collation) {
    op.collation = options.collation;
  }
 
  return op;
}
 
defineAspects(UpdateOperation, [Aspect.RETRYABLE, Aspect.WRITE_OPERATION, Aspect.SKIP_COLLATION]);
defineAspects(UpdateOneOperation, [
  Aspect.RETRYABLE,
  Aspect.WRITE_OPERATION,
  Aspect.EXPLAINABLE,
  Aspect.SKIP_COLLATION
]);
defineAspects(UpdateManyOperation, [
  Aspect.WRITE_OPERATION,
  Aspect.EXPLAINABLE,
  Aspect.SKIP_COLLATION
]);
defineAspects(ReplaceOneOperation, [
  Aspect.RETRYABLE,
  Aspect.WRITE_OPERATION,
  Aspect.SKIP_COLLATION
]);