diff --git a/index.js b/index.js index d6440d4..17160c8 100644 --- a/index.js +++ b/index.js @@ -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; @@ -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 }; } } @@ -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); }); });