Mongoose: use $type as the typeKey (#10789)

* use $type as the typeKey in mongoose

* fix and add tests
This commit is contained in:
Matteo Pagliazzi
2018-10-28 15:23:41 +01:00
committed by GitHub
parent 37b29d3449
commit dadb752087
15 changed files with 383 additions and 357 deletions

View File

@@ -3,10 +3,14 @@ import validator from 'validator';
import _ from 'lodash';
module.exports = function baseModel (schema, options = {}) {
if (schema.options.typeKey !== '$type') {
throw new Error('Every schema must use $type as the typeKey, see https://mongoosejs.com/docs/guide.html#typeKey');
}
if (options._id !== false) {
schema.add({
_id: {
type: String,
$type: String,
default: uuid,
validate: [v => validator.isUUID(v), 'Invalid uuid.'],
},
@@ -16,11 +20,11 @@ module.exports = function baseModel (schema, options = {}) {
if (options.timestamps) {
schema.add({
createdAt: {
type: Date,
$type: Date,
default: Date.now,
},
updatedAt: {
type: Date,
$type: Date,
default: Date.now,
},
});