From 02afe2ba7937cfb11745758cf04a582c8dd41332 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Tue, 2 Jul 2024 09:49:55 -0400 Subject: [PATCH 1/2] feat: allow setting array default value to `null` Fix #6691 --- docs/faq.md | 6 +++--- lib/schema/array.js | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/faq.md b/docs/faq.md index 8ae6a441b35..a0d493bc879 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -314,7 +314,7 @@ const Kitten = connection.model('Kitten', kittySchema); **Q**. How can I change mongoose's default behavior of initializing an array path to an empty array so that I can require real data on document creation? -**A**. You can set the default of the array to a function that returns `undefined`. +**A**. You can set the default of the array to `undefined`. ```javascript const CollectionSchema = new Schema({ @@ -329,13 +329,13 @@ const CollectionSchema = new Schema({ **Q**. How can I initialize an array path to `null`? -**A**. You can set the default of the array to a function that returns `null`. +**A**. You can set the default of the array to [`null`](https://masteringjs.io/tutorials/fundamentals/null). ```javascript const CollectionSchema = new Schema({ field1: { type: [String], - default: () => { return null; } + default: null } }); ``` diff --git a/lib/schema/array.js b/lib/schema/array.js index 67fe713a99b..00774ee3147 100644 --- a/lib/schema/array.js +++ b/lib/schema/array.js @@ -111,7 +111,7 @@ function SchemaArray(key, cast, options, schemaOptions) { fn = typeof defaultArr === 'function'; } - if (!('defaultValue' in this) || this.defaultValue !== void 0) { + if (!('defaultValue' in this) || this.defaultValue != null) { const defaultFn = function() { // Leave it up to `cast()` to convert the array return fn From b2f7ee4e02ba541129f08ee12a8ad1e965a7c0dc Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Thu, 4 Jul 2024 09:30:26 -0400 Subject: [PATCH 2/2] test: add test for setting array default value to null re: #6691 --- test/document.test.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/test/document.test.js b/test/document.test.js index f633a2ca75e..344ae9e5a7f 100644 --- a/test/document.test.js +++ b/test/document.test.js @@ -3198,6 +3198,23 @@ describe('document', function() { assert.ok(!('names' in doc)); }); + it('can set array default to null (gh-14717)', async function() { + const schema = new Schema({ + names: { + type: [String], + default: null + } + }); + + const Model = db.model('Test', schema); + const m = new Model(); + assert.strictEqual(m.names, null); + await m.save(); + + const doc = await Model.collection.findOne({ _id: m._id }); + assert.strictEqual(doc.names, null); + }); + it('validation works when setting array index (gh-3816)', async function() { const mySchema = new mongoose.Schema({ items: [