Skip to content

Commit a9800f4

Browse files
authored
Merge pull request #14717 from Automattic/vkarpov15/gh-6691
feat: allow setting array default value to `null`
2 parents 0e8525e + b2f7ee4 commit a9800f4

File tree

3 files changed

+21
-4
lines changed

3 files changed

+21
-4
lines changed

docs/faq.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -314,7 +314,7 @@ const Kitten = connection.model('Kitten', kittySchema);
314314

315315
<a class="anchor" href="#array-defaults">**Q**</a>. 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?
316316

317-
**A**. You can set the default of the array to a function that returns `undefined`.
317+
**A**. You can set the default of the array to `undefined`.
318318

319319
```javascript
320320
const CollectionSchema = new Schema({
@@ -329,13 +329,13 @@ const CollectionSchema = new Schema({
329329

330330
<a class="anchor" href="#initialize-array-path-null">**Q**</a>. How can I initialize an array path to `null`?
331331

332-
**A**. You can set the default of the array to a function that returns `null`.
332+
**A**. You can set the default of the array to [`null`](https://masteringjs.io/tutorials/fundamentals/null).
333333

334334
```javascript
335335
const CollectionSchema = new Schema({
336336
field1: {
337337
type: [String],
338-
default: () => { return null; }
338+
default: null
339339
}
340340
});
341341
```

lib/schema/array.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ function SchemaArray(key, cast, options, schemaOptions) {
111111
fn = typeof defaultArr === 'function';
112112
}
113113

114-
if (!('defaultValue' in this) || this.defaultValue !== void 0) {
114+
if (!('defaultValue' in this) || this.defaultValue != null) {
115115
const defaultFn = function() {
116116
// Leave it up to `cast()` to convert the array
117117
return fn

test/document.test.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3198,6 +3198,23 @@ describe('document', function() {
31983198
assert.ok(!('names' in doc));
31993199
});
32003200

3201+
it('can set array default to null (gh-14717)', async function() {
3202+
const schema = new Schema({
3203+
names: {
3204+
type: [String],
3205+
default: null
3206+
}
3207+
});
3208+
3209+
const Model = db.model('Test', schema);
3210+
const m = new Model();
3211+
assert.strictEqual(m.names, null);
3212+
await m.save();
3213+
3214+
const doc = await Model.collection.findOne({ _id: m._id });
3215+
assert.strictEqual(doc.names, null);
3216+
});
3217+
32013218
it('validation works when setting array index (gh-3816)', async function() {
32023219
const mySchema = new mongoose.Schema({
32033220
items: [

0 commit comments

Comments
 (0)