Skip to content

Commit

Permalink
Merge pull request #14717 from Automattic/vkarpov15/gh-6691
Browse files Browse the repository at this point in the history
feat: allow setting array default value to `null`
  • Loading branch information
vkarpov15 authored Jul 4, 2024
2 parents 0e8525e + b2f7ee4 commit a9800f4
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 4 deletions.
6 changes: 3 additions & 3 deletions docs/faq.md
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ const Kitten = connection.model('Kitten', kittySchema);

<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?

**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({
Expand All @@ -329,13 +329,13 @@ const CollectionSchema = new Schema({

<a class="anchor" href="#initialize-array-path-null">**Q**</a>. 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
}
});
```
Expand Down
2 changes: 1 addition & 1 deletion lib/schema/array.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 17 additions & 0 deletions test/document.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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: [
Expand Down

0 comments on commit a9800f4

Please sign in to comment.