* Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, * one will be added to each of the documents missing it by the driver, mutating the document. This behavior * can be overridden by setting the **forceServerObjectId** flag. * * @param d
(
docs: ReadonlyArray<OptionalUnlessRequiredId<TSchema>>,
options?: BulkWriteOptions
)
| 310 | * @param options - Optional settings for the command |
| 311 | */ |
| 312 | async insertMany( |
| 313 | docs: ReadonlyArray<OptionalUnlessRequiredId<TSchema>>, |
| 314 | options?: BulkWriteOptions |
| 315 | ): Promise<InsertManyResult<TSchema>> { |
| 316 | if (!Array.isArray(docs)) { |
| 317 | throw new MongoInvalidArgumentError('Argument "docs" must be an array of documents'); |
| 318 | } |
| 319 | options = resolveOptions(this, options ?? {}); |
| 320 | |
| 321 | const acknowledged = WriteConcern.fromOptions(options)?.w !== 0; |
| 322 | |
| 323 | try { |
| 324 | const res = await this.bulkWrite( |
| 325 | docs.map(doc => ({ insertOne: { document: doc } })), |
| 326 | options |
| 327 | ); |
| 328 | return { |
| 329 | acknowledged, |
| 330 | insertedCount: res.insertedCount, |
| 331 | insertedIds: res.insertedIds |
| 332 | }; |
| 333 | } catch (err) { |
| 334 | if (err && err.message === 'Operation must be an object with an operation key') { |
| 335 | throw new MongoInvalidArgumentError( |
| 336 | 'Collection.insertMany() cannot be called with an array that has null/undefined values' |
| 337 | ); |
| 338 | } |
| 339 | throw err; |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | /** |
| 344 | * Perform a bulkWrite operation without a fluent API |