Skip to content

Commit

Permalink
fix: add types and docs re: code review comments
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Mar 16, 2023
1 parent 1111f98 commit 27091c6
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 7 deletions.
18 changes: 13 additions & 5 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -3371,7 +3371,7 @@ Model.startSession = function() {
* @param {Array|Object|*} doc(s)
* @param {Object} [options] see the [mongodb driver options](https://mongodb.github.io/node-mongodb-native/4.9/classes/Collection.html#insertMany)
* @param {Boolean} [options.ordered=true] if true, will fail fast on the first error encountered. If false, will insert all the documents it can and report errors later. An `insertMany()` with `ordered = false` is called an "unordered" `insertMany()`.
* @param {Boolean} [options.rawResult=false] if false, the returned promise resolves to the documents that passed mongoose document validation. If `true`, will return the [raw result from the MongoDB driver](https://mongodb.github.io/node-mongodb-native/4.9/interfaces/InsertManyResult.html) with a `mongoose` property that contains `validationErrors` if this is an unordered `insertMany`.
* @param {Boolean} [options.rawResult=false] if false, the returned promise resolves to the documents that passed mongoose document validation. If `true`, will return the [raw result from the MongoDB driver](https://mongodb.github.io/node-mongodb-native/4.9/interfaces/InsertManyResult.html) with a `mongoose` property that contains `validationErrors` and `results` if this is an unordered `insertMany`.
* @param {Boolean} [options.lean=false] if `true`, skips hydrating and validating the documents. This option is useful if you need the extra performance, but Mongoose won't validate the documents before inserting.
* @param {Number} [options.limit=null] this limits the number of documents being processed (validation/casting) by mongoose in parallel, this does **NOT** send the documents in batches to MongoDB. Use this option if you're processing a large number of documents and your app is running out of memory.
* @param {String|Object|Array} [options.populate=null] populates the result documents. This option is a no-op if `rawResult` is set.
Expand Down Expand Up @@ -3534,19 +3534,20 @@ Model.$__insertMany = function(arr, options, callback) {
const erroredIndexes = new Set((error && error.writeErrors || []).map(err => err.index));

for (let i = 0; i < error.writeErrors.length; ++i) {
const originalIndex = validDocIndexToOriginalIndex.get(error.writeErrors[i].index);
error.writeErrors[i] = {
...error.writeErrors[i],
index: validDocIndexToOriginalIndex.get(error.writeErrors[i].index)
index: originalIndex
};
if (!ordered) {
results[validDocIndexToOriginalIndex.get(error.writeErrors[i].index)] = error.writeErrors[i];
results[originalIndex] = error.writeErrors[i];
}
}

if (!ordered) {
for (let i = 0; i < results.length; ++i) {
if (results[i] === void 0) {
results[i] = docAttributes[i];
results[i] = docs[i];
}
}

Expand Down Expand Up @@ -3594,10 +3595,17 @@ Model.$__insertMany = function(arr, options, callback) {

if (rawResult) {
if (ordered === false) {
for (let i = 0; i < results.length; ++i) {
if (results[i] === void 0) {
results[i] = docs[i];
}
}

// Decorate with mongoose validation errors in case of unordered,
// because then still do `insertMany()`
res.mongoose = {
validationErrors: validationErrors
validationErrors: validationErrors,
results: results
};
}
return callback(null, res);
Expand Down
13 changes: 13 additions & 0 deletions test/model.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4857,6 +4857,12 @@ describe('Model', function() {
assert.ok(!res.mongoose.validationErrors[0].errors['year']);
assert.ok(res.mongoose.validationErrors[1].errors['year']);
assert.ok(!res.mongoose.validationErrors[1].errors['name']);

assert.equal(res.mongoose.results.length, 3);
assert.ok(res.mongoose.results[0].errors['name']);
assert.ok(res.mongoose.results[1].errors['year']);
assert.ok(res.mongoose.results[2].$__);
assert.equal(res.mongoose.results[2].name, 'The Empire Strikes Back');
});

it('insertMany() validation error with ordered false and rawResult for mixed write and validation error (gh-12791)', async function() {
Expand Down Expand Up @@ -4886,6 +4892,13 @@ describe('Model', function() {
assert.ok(!err.mongoose.validationErrors[0].errors['year']);
assert.ok(err.mongoose.validationErrors[1].errors['year']);
assert.ok(!err.mongoose.validationErrors[1].errors['name']);

assert.equal(err.mongoose.results.length, 4);
assert.ok(err.mongoose.results[0].errors['name']);
assert.ok(err.mongoose.results[1].errors['year']);
assert.ok(err.mongoose.results[2].$__);
assert.equal(err.mongoose.results[2].name, 'The Empire Strikes Back');
assert.ok(err.mongoose.results[3].err);
});

it('insertMany() populate option (gh-9720)', async function() {
Expand Down
7 changes: 5 additions & 2 deletions test/types/models.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,18 +87,21 @@ async function insertManyTest() {
foo: string;
}

const TestSchema = new Schema<ITest & Document>({
const TestSchema = new Schema<ITest>({
foo: { type: String, required: true }
});

const Test = connection.model<ITest & Document>('Test', TestSchema);
const Test = connection.model<ITest>('Test', TestSchema);

Test.insertMany([{ foo: 'bar' }]).then(async res => {
res.length;
});

const res = await Test.insertMany([{ foo: 'bar' }], { rawResult: true });
expectType<ObjectId>(res.insertedIds[0]);

const res2 = await Test.insertMany([{ foo: 'bar' }], { ordered: false, rawResult: true });
expectAssignable<Error | Object | ReturnType<(typeof Test)['hydrate']>>(res2.mongoose.results[0]);
}

function schemaStaticsWithoutGenerics() {
Expand Down
9 changes: 9 additions & 0 deletions types/models.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,15 @@ declare module 'mongoose' {
insertMany<DocContents = T>(doc: DocContents, callback: Callback<Array<HydratedDocument<MergeType<MergeType<T, DocContents>, Require_id<T>>, TMethodsAndOverrides, TVirtuals>>>): void;

insertMany<DocContents = T>(docs: Array<DocContents | T>, options: InsertManyOptions & { lean: true; }): Promise<Array<MergeType<MergeType<T, DocContents>, Require_id<T>>>>;
insertMany<DocContents = T>(
doc: DocContents,
options: InsertManyOptions & { ordered: false; rawResult: true; }
): Promise<mongodb.InsertManyResult<T> & {
mongoose: {
validationErrors: Error[];
results: Array<Error | Object | HydratedDocument<MergeType<MergeType<T, DocContents>, Require_id<T>>, TMethodsAndOverrides, TVirtuals>>
}
}>;
insertMany<DocContents = T>(docs: Array<DocContents | T>, options: InsertManyOptions & { rawResult: true; }): Promise<mongodb.InsertManyResult<T>>;
insertMany<DocContents = T>(docs: Array<DocContents | T>): Promise<Array<HydratedDocument<MergeType<MergeType<T, DocContents>, Require_id<T>>, TMethodsAndOverrides, TVirtuals>>>;
insertMany<DocContents = T>(doc: DocContents, options: InsertManyOptions & { lean: true; }): Promise<Array<MergeType<MergeType<T, DocContents>, Require_id<T>>>>;
Expand Down

0 comments on commit 27091c6

Please sign in to comment.