Skip to content

Commit

Permalink
Merge branch 'master' into gh-9850
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Mar 2, 2021
2 parents 321ead5 + bf5a96f commit 07404db
Show file tree
Hide file tree
Showing 13 changed files with 84 additions and 45 deletions.
25 changes: 0 additions & 25 deletions .travis.yml

This file was deleted.

12 changes: 12 additions & 0 deletions History.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
5.11.18 / 2021-02-23
====================
* fix(connection): set connection state to `disconnected` if connecting string failed to parse #9921
* fix(connection): remove `db` events deprecation warning if `useUnifiedTopology = true` #9930
* fix(connection): fix promise chaining for openUri #9960 [lantw44](https://github.com/lantw44)
* fix(index.d.ts): add `PopulatedDoc` type to make it easier to define populated docs in interfaces #9818
* fix(index.d.ts): allow explicitly overwriting `toObject()` return type for backwards compatibility #9944
* fix(index.d.ts): correctly throw error when interface path type doesn't line up with schema path type #9958 [ShadiestGoat](https://github.com/ShadiestGoat)
* fix(index.d.ts): remove `any` from `deleteX()` and `updateX()` query params and return values #9959 [btd](https://github.com/btd)
* fix(index.d.ts): add non-generic versions of `Model.create()` for better autocomplete #9928
* docs: correctly handle multiple `&gt` in API descriptions #9940

5.11.17 / 2021-02-17
====================
* fix(populate): handle `perDocumentLimit` when multiple documents reference the same populated doc #9906
Expand Down
2 changes: 1 addition & 1 deletion docs/populate.pug
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ block content
// prints "The author is Ian Fleming"

console.log('The authors age is %s', story.author.age);
// prints "The authors age is null'
// prints "The authors age is null"
});
```

Expand Down
11 changes: 8 additions & 3 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1189,9 +1189,9 @@ declare module 'mongoose' {
}

type SchemaDefinitionWithBuiltInClass<T extends number | string | Function> = T extends number
? (typeof Number | 'number' | 'Number')
? (typeof Number | 'number' | 'Number' | typeof Schema.Types.Number)
: T extends string
? (typeof String | 'string' | 'String')
? (typeof String | 'string' | 'String' | typeof Schema.Types.String)
: (Function | string);

type SchemaDefinitionProperty<T = undefined> = T extends string | number | Function
Expand Down Expand Up @@ -1371,8 +1371,13 @@ declare module 'mongoose' {
currentTime?: () => (Date | number);
}

type Unpacked<T> = T extends (infer U)[] ? U : T;

interface SchemaTypeOptions<T> {
type?: T extends string | number | Function ? SchemaDefinitionWithBuiltInClass<T> : T;
type?:
T extends string | number | Function ? SchemaDefinitionWithBuiltInClass<T> :
T extends object[] ? T | Schema<Unpacked<T> & Document>[] :
T;

/** Defines a virtual with the given name that gets/sets this path. */
alias?: string;
Expand Down
6 changes: 0 additions & 6 deletions index.pug
Original file line number Diff line number Diff line change
Expand Up @@ -169,9 +169,6 @@ html(lang='en')
<a rel="sponsored" href="https://localizejs.com/">
<img class="sponsor" src="https://images.opencollective.com/localize/bb2cd4d/logo/256.png" style="height: 100px">
</a>
<a rel="sponsored" href="https://payment.ninja/partners/mongoose/?ref=5e2c6ea94e9158a6d2cc2af2">
<img class="sponsor" src="https://codebarbarian-images.s3.amazonaws.com/payment-ninja-mongoose.png" style="height: 100px">
</a>
<a rel="sponsored" href="https://www.codefirst.co.uk/">
<img class="sponsor" src="https://images.opencollective.com/proxy/images?src=https%3A%2F%2Fopencollective-production.s3-us-west-1.amazonaws.com%2Fdde88120-e914-11e8-a662-278259d35390.png&height=100">
</a>
Expand Down Expand Up @@ -259,9 +256,6 @@ html(lang='en')
<a rel="sponsored" href="https://taxfreesnus.com/">
<img class="sponsor" src="https://images.opencollective.com/taxfreesnus-com/ebf869a/logo.png" style="height: 100px">
</a>
<a rel="sponsored" href="https://www.nettikasinot.org/">
<img class="sponsor" src="https://images.opencollective.com/nettikasinot-org/bbd887f/logo/256.png" style="height: 100px">
</a>
<a rel="sponsored" href="https://www.pelisivut.com/">
<img class="sponsor" src="https://images.opencollective.com/pelisivut/04f08f2/logo/256.png" style="height: 100px">
</a>
Expand Down
6 changes: 4 additions & 2 deletions lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -2500,7 +2500,8 @@ Document.prototype.$__validate = function(pathsToValidate, options, callback) {

const doValidateOptions = {
skipSchemaValidators: skipSchemaValidators[path],
path: path
path: path,
validateModifiedOnly: shouldValidateModifiedOnly
};
schemaType.doValidate(val, function(err) {
if (err && (!schemaType.$isMongooseDocumentArray || err.$isArrayValidatorError)) {
Expand Down Expand Up @@ -2626,7 +2627,8 @@ Document.prototype.validateSync = function(pathsToValidate, options) {
const val = _this.$__getValue(path);
const err = p.doValidateSync(val, _this, {
skipSchemaValidators: skipSchemaValidators[path],
path: path
path: path,
validateModifiedOnly: shouldValidateModifiedOnly
});
if (err && (!p.$isMongooseDocumentArray || err.$isArrayValidatorError)) {
if (p.$isSingleNested &&
Expand Down
7 changes: 7 additions & 0 deletions lib/helpers/timestamps/setupTimestamps.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ module.exports = function setupTimestamps(schema, timestamps) {
_setTimestampsOnUpdate[symbols.builtInMiddleware] = true;

const opts = { query: true, model: false };
schema.pre('findOneAndReplace', opts, _setTimestampsOnUpdate);
schema.pre('findOneAndUpdate', opts, _setTimestampsOnUpdate);
schema.pre('replaceOne', opts, _setTimestampsOnUpdate);
schema.pre('update', opts, _setTimestampsOnUpdate);
Expand All @@ -96,6 +97,12 @@ module.exports = function setupTimestamps(schema, timestamps) {
const now = currentTime != null ?
currentTime() :
this.model.base.now();

// Replacing with null update should still trigger timestamps
if (this.op === 'findOneAndReplace' && this.getUpdate() == null) {
this.setUpdate({});
}

applyTimestampsToUpdate(now, createdAt, updatedAt, this.getUpdate(),
this.options, this.schema);
applyTimestampsToChildren(now, this.getUpdate(), this.model.schema);
Expand Down
1 change: 1 addition & 0 deletions lib/query.js
Original file line number Diff line number Diff line change
Expand Up @@ -3331,6 +3331,7 @@ Query.prototype.findOneAndReplace = function(filter, replacement, options, callb
}

this.setOptions(options);
this.setOptions({ overwrite: true });

if (!callback) {
return this;
Expand Down
11 changes: 10 additions & 1 deletion lib/schema/documentarray.js
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,11 @@ DocumentArrayPath.prototype.doValidate = function(array, fn, scope, options) {
doc = array[i] = new Constructor(doc, array, undefined, undefined, i);
}

if (options.validateModifiedOnly && !doc.isModified()) {
--count || fn(error);
continue;
}

doc.$__validate(callback);
}
}
Expand All @@ -267,7 +272,7 @@ DocumentArrayPath.prototype.doValidate = function(array, fn, scope, options) {
* @api private
*/

DocumentArrayPath.prototype.doValidateSync = function(array, scope) {
DocumentArrayPath.prototype.doValidateSync = function(array, scope, options) {
const schemaTypeError = SchemaType.prototype.doValidateSync.call(this, array, scope);
if (schemaTypeError != null) {
schemaTypeError.$isArrayValidatorError = true;
Expand Down Expand Up @@ -299,6 +304,10 @@ DocumentArrayPath.prototype.doValidateSync = function(array, scope) {
doc = array[i] = new Constructor(doc, array, undefined, undefined, i);
}

if (options != null && options.validateModifiedOnly && !doc.isModified()) {
continue;
}

const subdocValidateError = doc.validateSync();

if (subdocValidateError && resultError == null) {
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "mongoose",
"description": "Mongoose MongoDB ODM",
"version": "5.11.17",
"version": "5.11.18",
"author": "Guillermo Rauch <[email protected]>",
"keywords": [
"mongodb",
Expand Down Expand Up @@ -63,7 +63,7 @@
"pug": "2.0.3",
"q": "1.5.1",
"semver": "5.5.0",
"typescript": "4.x",
"typescript": "4.1.x",
"uuid": "2.0.3",
"uuid-parse": "1.0.0",
"validator": "10.8.0",
Expand Down
12 changes: 9 additions & 3 deletions test/document.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2519,15 +2519,21 @@ describe('document', function() {
});
});

it('filters out validation on unmodified paths when validateModifiedOnly set (gh-7421)', function(done) {
const testSchema = new Schema({ title: { type: String, required: true }, other: String });
it('filters out validation on unmodified paths when validateModifiedOnly set (gh-7421) (gh-9963)', function(done) {
const testSchema = new Schema({
title: { type: String, required: true },
other: String,
subdocs: [{ name: { type: String, required: true } }]
});

const Test = db.model('Test', testSchema);

Test.create([{}], { validateBeforeSave: false }, function(createError, docs) {
const doc = { subdocs: [{ name: null }, { name: 'test' }] };
Test.create([doc], { validateBeforeSave: false }, function(createError, docs) {
assert.equal(createError, null);
const doc = docs[0];
doc.other = 'something';
doc.subdocs[1].name = 'test2';
assert.equal(doc.validateSync(undefined, { validateModifiedOnly: true }), null);
doc.save({ validateModifiedOnly: true }, function(error) {
assert.equal(error, null);
Expand Down
10 changes: 9 additions & 1 deletion test/timestamps.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -582,7 +582,7 @@ describe('timestamps', function() {
});
});

it('should have fields when create with findOneAndUpdate', function(done) {
it('sets timestamps on findOneAndUpdate', function(done) {
Cat.findOneAndUpdate({ name: 'notexistname' }, { $set: {} }, { upsert: true, new: true }, function(err, doc) {
assert.ok(doc.createdAt);
assert.ok(doc.updatedAt);
Expand All @@ -591,6 +591,14 @@ describe('timestamps', function() {
});
});

it('sets timestamps on findOneAndReplace (gh-9951)', function() {
return Cat.findOneAndReplace({ name: 'notexistname' }, {}, { upsert: true, new: true }).then(doc => {
assert.ok(doc.createdAt);
assert.ok(doc.updatedAt);
assert.ok(doc.createdAt.getTime() === doc.updatedAt.getTime());
});
});

it('should change updatedAt when save', function(done) {
Cat.findOne({ name: 'newcat' }, function(err, doc) {
const old = doc.updatedAt;
Expand Down
22 changes: 21 additions & 1 deletion test/typescript/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,23 @@ enum Genre {
Comedy
}

const movieSchema: Schema = new Schema({
interface Actor {
name: string,
age: number
}
const actorSchema =
new Schema<Actor & Document, Model<Actor & Document>, Actor>({ name: { type: String }, age: { type: Number } });

interface Movie {
title?: string,
featuredIn?: string,
rating?: number,
genre?: string,
actionIntensity?: number,
actors?: Actor[]
}

const movieSchema = new Schema<Document<Movie>, Model<Document<Movie>>, Movie>({
title: String,
featuredIn: {
type: String,
Expand All @@ -32,6 +48,10 @@ const movieSchema: Schema = new Schema({
},
'Action intensity required for action genre'
]
},
actors: {
type: [actorSchema],
default: undefined
}
});

Expand Down

0 comments on commit 07404db

Please sign in to comment.