Skip to content

Commit

Permalink
Merge branch '6.0' into gh-9840
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Jan 26, 2021
2 parents 4b4572a + 6b60a94 commit 3e8b810
Show file tree
Hide file tree
Showing 16 changed files with 116 additions and 27 deletions.
4 changes: 2 additions & 2 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -546,7 +546,7 @@ declare module 'mongoose' {
populated(path: string): any;

/** Removes this document from the db. */
remove(options?: QueryOptions): Query<any, this>;
remove(options?: QueryOptions): Promise<this>;
remove(options?: QueryOptions, cb?: (err: CallbackError, res: any) => void): void;

/** Sends a replaceOne command with this document `_id` as the query selector. */
Expand Down Expand Up @@ -1421,7 +1421,7 @@ declare module 'mongoose' {
set?: (value: T, schematype?: this) => any;

/** array of allowed values for this path. Allowed for strings, numbers, and arrays of strings */
enum?: Array<string | number | null>
enum?: Array<string | number | null> | { [path: string]: string | number | null };

/** The default [subtype](http://bsonspec.org/spec.html) associated with this buffer when it is stored in MongoDB. Only allowed for buffer paths */
subtype?: number
Expand Down
3 changes: 3 additions & 0 deletions index.pug
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,9 @@ html(lang='en')
<a rel="sponsored" href="https://www.nettikasinot.media/">
<img class="sponsor" src="https://images.opencollective.com/nettikasinot-media/2dba7da/logo/256.png" style="height: 100px">
</a>
<a rel="sponsored" href="https://kajino.com/">
<img class="sponsor" src="https://images.opencollective.com/kajino-com/02c99ee/logo/256.png" style="height: 100px">
</a>
</div>
</div>

Expand Down
4 changes: 1 addition & 3 deletions lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ const isMongooseObject = utils.isMongooseObject;
const arrayAtomicsBackupSymbol = Symbol('mongoose.Array#atomicsBackup');
const arrayAtomicsSymbol = require('./helpers/symbols').arrayAtomicsSymbol;
const documentArrayParent = require('./helpers/symbols').documentArrayParent;
const documentIsSelected = require('./helpers/symbols').documentIsSelected;
const documentIsModified = require('./helpers/symbols').documentIsModified;
const documentModifiedPaths = require('./helpers/symbols').documentModifiedPaths;
const documentSchemaSymbol = require('./helpers/symbols').documentSchemaSymbol;
Expand Down Expand Up @@ -2109,7 +2108,7 @@ Document.prototype.isSelected = function isSelected(path) {
return !inclusive;
};

Document.prototype[documentIsSelected] = Document.prototype.isSelected;
Document.prototype.$__isSelected = Document.prototype.isSelected;

/**
* Checks if `path` was explicitly selected. If no projection, always returns
Expand Down Expand Up @@ -4055,7 +4054,6 @@ Document.prototype.$__fullPath = function(path) {

Document.prototype.getChanges = function() {
const delta = this.$__delta();

const changes = delta ? delta[1] : {};
return changes;
};
Expand Down
3 changes: 2 additions & 1 deletion lib/error/validation.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,13 +67,14 @@ if (util.inspect.custom) {

/*!
* Helper for JSON.stringify
* Ensure `name` and `message` show up in toJSON output re: gh-9847
*/
Object.defineProperty(ValidationError.prototype, 'toJSON', {
enumerable: false,
writable: false,
configurable: true,
value: function() {
return Object.assign({}, this, { message: this.message });
return Object.assign({}, this, { name: this.name, message: this.message });
}
});

Expand Down
2 changes: 0 additions & 2 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -536,7 +536,6 @@ function operand(self, where, delta, data, val, op) {
op || (op = '$set');
if (!delta[op]) delta[op] = {};
delta[op][data.path] = val;

// disabled versioning?
if (self.schema.options.versionKey === false) return;

Expand Down Expand Up @@ -746,7 +745,6 @@ Model.prototype.$__delta = function() {
if (this.$__.version) {
this.$__version(where, delta);
}

return [where, delta];
};

Expand Down
8 changes: 4 additions & 4 deletions lib/schema/SingleNestedPath.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ SingleNestedPath.prototype.$conditionalHandlers.$exists = $exists;
* @api private
*/

SingleNestedPath.prototype.cast = function(val, doc, init, priorVal) {
SingleNestedPath.prototype.cast = function(val, doc, init, priorVal, options) {
if (val && val.$isSingleNested && val.parent === doc) {
return val;
}
Expand All @@ -169,16 +169,16 @@ SingleNestedPath.prototype.cast = function(val, doc, init, priorVal) {
}
return obj;
}, {});

options = Object.assign({}, options, { priorDoc: priorVal });
if (init) {
subdoc = new Constructor(void 0, selected, doc);
subdoc.init(val);
} else {
if (Object.keys(val).length === 0) {
return new Constructor({}, selected, doc, undefined, { priorDoc: priorVal });
return new Constructor({}, selected, doc, undefined, options);
}

return new Constructor(val, selected, doc, undefined, { priorDoc: priorVal });
return new Constructor(val, selected, doc, undefined, options);
}

return subdoc;
Expand Down
2 changes: 1 addition & 1 deletion lib/schema/array.js
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,7 @@ SchemaArray.prototype.cast = function(value, doc, init, prev, options) {
}

const isPopulated = doc != null && doc.$__ != null && doc.populated(this.path);
if (isPopulated) {
if (isPopulated && init) {
return value;
}

Expand Down
4 changes: 1 addition & 3 deletions lib/schematype.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ const schemaTypeSymbol = require('./helpers/symbols').schemaTypeSymbol;
const util = require('util');
const utils = require('./utils');
const validatorErrorSymbol = require('./helpers/symbols').validatorErrorSymbol;

const documentIsSelected = require('./helpers/symbols').documentIsSelected;
const documentIsModified = require('./helpers/symbols').documentIsModified;

const CastError = MongooseError.CastError;
Expand Down Expand Up @@ -953,7 +951,7 @@ SchemaType.prototype.required = function(required, message) {
const cachedRequired = get(this, '$__.cachedRequired');

// no validation when this path wasn't selected in the query.
if (cachedRequired != null && !this[documentIsSelected](_this.path) && !this[documentIsModified](_this.path)) {
if (cachedRequired != null && !this.$__isSelected(_this.path) && !this[documentIsModified](_this.path)) {
return true;
}

Expand Down
3 changes: 1 addition & 2 deletions lib/types/map.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ class MongooseMap extends Map {
v = Object.keys(v).reduce((arr, key) => arr.concat([[key, v[key]]]), []);
}
super(v);

this.$__parent = doc != null && doc.$__ != null ? doc : null;
this.$__path = path;
this.$__schemaType = schemaType == null ? new Mixed(path) : schemaType;
Expand Down Expand Up @@ -77,7 +76,7 @@ class MongooseMap extends Map {
} else {
try {
value = this.$__schemaType.
applySetters(value, this.$__parent, false, this.get(key));
applySetters(value, this.$__parent, false, this.get(key), { path: fullPath });
} catch (error) {
if (this.$__parent != null && this.$__parent.$__ != null) {
this.$__parent.invalidate(fullPath, error);
Expand Down
1 change: 0 additions & 1 deletion lib/types/subdocument.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ module.exports = Subdocument;

function Subdocument(value, fields, parent, skipId, options) {
this.$isSingleNested = true;

if (parent != null) {
// If setting a nested path, should copy isNew from parent re: gh-7048
const parentOptions = { isNew: parent.isNew, defaults: parent.$__.$options.defaults };
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,8 @@
],
"rules": {
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/ban-types": "off"
"@typescript-eslint/ban-types": "off",
"@typescript-eslint/no-unused-vars": "off"
}
}
],
Expand Down
28 changes: 28 additions & 0 deletions test/document.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9877,4 +9877,32 @@ describe('document', function() {
assert.ok(!_doc);
});
});

it('object setters will be applied for each object in array after populate (gh-9838)', function() {
const updatedElID = '123456789012345678901234';

const ElementSchema = new Schema({
name: 'string',
nested: [{ type: Schema.Types.ObjectId, ref: 'Nested' }]
});

const NestedSchema = new Schema({});

const Element = db.model('Test', ElementSchema);
const NestedElement = db.model('Nested', NestedSchema);

return co(function*() {
const nes = new NestedElement({});
yield nes.save();
const ele = new Element({ nested: [nes.id], name: 'test' });
yield ele.save();

const ss = yield Element.findById(ele._id).populate({ path: 'nested', model: NestedElement });
ss.nested = [updatedElID];
yield ss.save();

assert.ok(typeof ss.nested[0] !== 'string');
assert.equal(ss.nested[0].toHexString(), updatedElID);
});
});
});
27 changes: 27 additions & 0 deletions test/types.map.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -977,6 +977,33 @@ describe('Map', function() {
});
});

it('tracks changes correctly (gh-9811)', function() {
const SubSchema = Schema({
myValue: {
type: String
}
}, { _id: false });
const schema = Schema({
myMap: {
type: Map,
of: {
type: SubSchema
}
// required: true
}
}, { minimize: false, collection: 'test' });
const Model = db.model('Test', schema);
return co(function*() {
const doc = yield Model.create({
myMap: new Map()
});
doc.myMap.set('abc', { myValue: 'some value' });
const changes = doc.getChanges();
assert.ok(!changes.$unset);
assert.deepEqual(changes, { $set: { 'myMap.abc': { myValue: 'some value' } } });
});
});

it('handles map of arrays (gh-9813)', function() {
const BudgetSchema = new mongoose.Schema({
budgeted: {
Expand Down
18 changes: 18 additions & 0 deletions test/typescript/document.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Schema, model, Document } from 'mongoose';

const schema: Schema = new Schema({ name: { type: 'String' } });

interface ITestBase {
name?: string;
}

interface ITest extends ITestBase, Document {}

const Test = model<ITest>('Test', schema);

void async function main() {
const doc: ITest = await Test.findOne().orFail();

const p: Promise<ITest> = doc.remove();
await p;
}();
10 changes: 9 additions & 1 deletion test/typescript/main.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,15 @@ describe('typescript syntax', function() {
});

it('schema', function() {
const errors = runTest('schema.ts');
const errors = runTest('schema.ts', { strict: true });
if (process.env.D && errors.length) {
console.log(errors);
}
assert.equal(errors.length, 0);
});

it('document', function() {
const errors = runTest('document.ts', { strict: true });
if (process.env.D && errors.length) {
console.log(errors);
}
Expand Down
23 changes: 17 additions & 6 deletions test/typescript/schema.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,27 @@
import { Schema } from 'mongoose';

const schema: Schema = new Schema({
name: String,
enumWithNull: {
enum Genre {
Action,
Adventure,
Comedy
}

const movieSchema: Schema = new Schema({
title: String,
featuredIn: {
type: String,
enum: ['Test', null],
enum: ['Favorites', null],
default: null
},
numberWithMax: {
rating: {
type: Number,
required: [true, 'Required'],
min: [0, 'MinValue'],
max: [24, 'MaxValue']
max: [5, 'MaxValue']
},
genre: {
type: String,
enum: Genre,
required: true
}
});

0 comments on commit 3e8b810

Please sign in to comment.