Skip to content

Commit 38eb5aa

Browse files
authored
Merge pull request #8365 from Fonger/fix/insertMany-cast
Correctly catch the error when insertMany fails to initialize the document
2 parents dc9272c + b5b21fb commit 38eb5aa

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

lib/model.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3206,10 +3206,15 @@ Model.$__insertMany = function(arr, options, callback) {
32063206

32073207
const toExecute = [];
32083208
const validationErrors = [];
3209+
32093210
arr.forEach(function(doc) {
32103211
toExecute.push(function(callback) {
32113212
if (!(doc instanceof _this)) {
3212-
doc = new _this(doc);
3213+
try {
3214+
doc = new _this(doc);
3215+
} catch (err) {
3216+
return callback(err);
3217+
}
32133218
}
32143219
if (options.session != null) {
32153220
doc.$session(options.session);

test/model.test.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4909,6 +4909,18 @@ describe('Model', function() {
49094909
});
49104910
});
49114911

4912+
it('insertMany() with non object array error can be catched (gh-8363)', function(done) {
4913+
const schema = mongoose.Schema({
4914+
_id: mongoose.Schema.Types.ObjectId,
4915+
url: { type: String }
4916+
});
4917+
const Image = db.model('gh8363', schema);
4918+
Image.insertMany(['a', 'b', 'c']).catch((error) => {
4919+
assert.equal(error.name, 'ObjectParameterError');
4920+
done();
4921+
});
4922+
});
4923+
49124924
it('insertMany() return docs with empty modifiedPaths (gh-7852)', function() {
49134925
const schema = new Schema({
49144926
name: { type: String }

0 commit comments

Comments
 (0)