Search code examples
mongooseuniquemodel-validationmongoose-models

Mongoose: Cannot read property 'where' of undefined, _id


I've got that model:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var uniqueValidator = require('mongoose-unique-validator');

var EquipmentSchema = new Schema({
    model: { type: String, required: true, unique: true},
    price: { type: Number, required: true },
    comments: { type: String },
    market: { type: mongoose.Types.ObjectId, ref: 'Market', required: true },
    category: { type: mongoose.Types.ObjectId, ref: 'Category', required: true },
    make: { type: mongoose.Types.ObjectId, ref: 'Make', required: true },
    rv: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Rv'}],
});

EquipmentSchema.plugin(uniqueValidator);
module.exports = mongoose.model('Equipments', EquipmentSchema);

This function to save new items:

const Equipments = require('./_models/equipment.model');

var equipmentSaver = function(equipment) {
  return new Promise((resolve, reject) => {
    console.log(equipment);
    const equipmentToSave = new Equipments({
      _id: equipment.type.model._id,
      market: equipment.type.market._id,
      category: equipment.type.category._id,
      make: equipment.type.make._id,
      model: equipment.type.model.name,
      price: equipment.economicDetails.price,
      comments: equipment.economicDetails.comments,
    });
    equipmentToSave.save()
      .then(result => resolve(result))
      .catch(error => reject(error))
   });
}

module.exports = equipmentSaver;

And I'm getting that JSON from the front:

{
  type: {
    market: {
      _id: '5eb1a63926849bed71155592',
      name: 'Healthcare',
      icon: 'local_hospital'
    },
    category: {
      _id: '5eb19f080141dbe4b9aebc9a',
      name: 'Diagnostico por la imagen',
      market: '5eb1a63926849bed71155592'
    },
    make: {
      _id: '5ebd3e107002040000e70e53',
      name: 'GE',
      category: '5eb19f080141dbe4b9aebc9a'
    },
    model: {
      _id: '5ebd3e167002040000e70e54',
      name: 'Voluson S8',
      make: '5ebd3e107002040000e70e53'
    }
  },
  economicDetails: {
    comments: 'Description',
    price: 45000,
    used: false
  }
}

All the _ids are created by the front and I get these 2 errors: 1.

Error [ValidationError]: Equipments validation failed: _id: Cannot read property 'where' of undefined, model: Cannot read property 'where' of undefined
    at ValidationError.inspect
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
      message: "Cannot read property 'where' of undefined",
      name: 'ValidatorError',
      properties: [Object],
      kind: 'unique',
      path: '_id',
      value: 5ebd3e167002040000e70e54,
      reason: TypeError: Cannot read property 'where' of undefined

2.

MongooseError [ValidatorError]: Cannot read property 'where' of undefined
        at new ValidatorError
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
      message: "Cannot read property 'where' of undefined",
      name: 'ValidatorError',
      properties: [Object],
      kind: 'unique',
      path: 'model',
      value: 'Voluson S8',
      reason: TypeError: Cannot read property 'where' of undefined

I have no idea why. I feel this has something to do with the "unique" character of both these fields but I'm not sure why it throws this error...

EDIT: I've found the origin of the error. When I deleted the EquipmentSchema.plugin(uniqueValidator); from my model, it saves correctly again... I've created an issue on mongoose-unique-validator's github but if anyone here has had the same problem or even has a solution that'd be great!

Thanks!


Solution

  • I found that the problem comes from the name of one of your fields : the model field in the EquipmentSchema

    var EquipmentSchema = new Schema({
        //this throws Cannot read property 'where' of undefined
        model: { type: String, required: true, unique: true} 
        ...
    })
    

    When you rename this field to something else or remove it, the plugin works just fine. Still, it's the mongoose-unique-validator plugin issue because model is not in the list of reserved document keys of mongoose.

    By looking in this section of the plugin code (the latest release), you can see there are if ... else if ... conditions to find the model, and defining a field named model as you did, makes all the conditions fail and leaves the model variable undefined which finally throws the error.