Skip to content

Commit

Permalink
Simplifies conditions object
Browse files Browse the repository at this point in the history
  • Loading branch information
viveleroi committed Apr 17, 2019
1 parent 7f41cd5 commit b8f3e0f
Showing 1 changed file with 8 additions and 7 deletions.
15 changes: 8 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ module.exports = function(schema, options) {
const parentDoc = isSubdocument ? this.ownerDocument() : this;
const isNew = typeof parentDoc.isNew === 'boolean' ? parentDoc.isNew : !isQuery;

let conditions = [];
const conditions = {};
each(paths, (name) => {
let pathValue;

Expand All @@ -75,17 +75,17 @@ module.exports = function(schema, options) {
pathValue = new RegExp('^' + pathValue + '$', 'i');
}

conditions.push({ [name]: pathValue });
conditions[name] = pathValue;
});

if (!isNew) {
// Use conditions the user has with find*AndUpdate
if (isQuery) {
each(this._conditions, (value, key) => {
conditions.push({ [key]: { $ne: value } });
conditions[key] = { $ne: value };
});
} else if (this._id) {
conditions.push({ _id: { $ne: this._id } });
conditions._id = { $ne: this._id };
}
}

Expand All @@ -100,14 +100,15 @@ module.exports = function(schema, options) {
} else if (isFunc(this.model)) {
model = this.model(this.constructor.modelName);
}

// Is this model a discriminator and the unique index is on the whole collection,
// not just the instances of the discriminator? If so, use the base model to query.
// https://github.com/Automattic/mongoose/issues/4965
if (model.baseModelName && indexOptions.partialFilterExpression == null) {
model = model.db.model(model.baseModelName);
if (model.baseModelName && indexOptions.partialFilterExpression === null) {
model = model.db.model(model.baseModelName);
}

model.where({ $and: conditions }).countDocuments((err, count) => {
model.find(conditions).countDocuments((err, count) => {
resolve(count === 0);
});
});
Expand Down

0 comments on commit b8f3e0f

Please sign in to comment.