Skip to content

Instantly share code, notes, and snippets.

@binki
Created August 11, 2017 02:51
Show Gist options
  • Save binki/3e306bc5ca3f5dcea9339accd39e0718 to your computer and use it in GitHub Desktop.
Save binki/3e306bc5ca3f5dcea9339accd39e0718 to your computer and use it in GitHub Desktop.
Mongoose way to get array to default to null
const assert = require('assert');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test-mongoose-default-null');
describe('mongoose', function () {
for (const {id, buildSchema, } of [
{
id: 'FooNull',
buildSchema: () => new mongoose.Schema({
bar: {
type: [Number, ],
default: null,
},
}),
},
{
id: 'FooUndefined',
buildSchema: () => new mongoose.Schema({
bar: {
type: [Number, ],
default: undefined,
},
}),
},
{
id: 'FooQueue',
buildSchema: () => {
const FooSchema = new mongoose.Schema({
bar: {
type: [Number, ],
},
});
FooSchema.methods.postconstructed = function () {
this.bar = null;
};
FooSchema.queue('postconstructed');
return FooSchema;
},
},
]) {
it(`should allow default:null for array (${id})`, async function () {
const FooSchema = buildSchema();
const Foo = mongoose.model(id, FooSchema);
const foo = new Foo();
assert.strictEqual(foo.bar, null);
await foo.save();
const loadedFoo = await Foo.findById(foo._id);
assert.strictEqual(loadedFoo.bar, null);
});
}
});
ohnobinki@gibby ~/mongoose-defaultnull-play $ ./node_modules/.bin/mocha index.test.js
(node:5768) DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`. See http://mongoosejs.com/docs/connections.html#use-mongo-client
mongoose
1) should allow default:null for array (FooNull)
2) should allow default:null for array (FooUndefined)
(node:5768) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
✓ should allow default:null for array (FooQueue)
1 passing (95ms)
2 failing
1) mongoose should allow default:null for array (FooNull):
AssertionError [ERR_ASSERTION]: [] === null
at Context.<anonymous> (index.test.js:46:14)
2) mongoose should allow default:null for array (FooUndefined):
AssertionError [ERR_ASSERTION]: undefined === null
at Context.<anonymous> (index.test.js:46:14)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment