dmr07
dmr07

Reputation: 1478

Mongoose Schema Type String not working

I'm updating on my database, but I'm having trouble understanding what is happening with my schema below:

{ 
  ref             : String,
  event           : {
    name          : String,
    data          : mongoose.Schema.Types.Mixed,
    type          : mongoose.Schema.Types.Mixed, // Declaring this as String makes parent(event) undefined. 
  }
}

The input data to event.type are strings, but when I declare it as such, the event field for all existing and new documents become undefined.

i.e. in the Main Function (below) I get Cannot set property 'type' of undefined

// Main function
model
  .find({ 'event.type' : { $exists: false }})
  .exec(function(err, data) {
    if (err) return console.log(err);

    for (var i = 0, len = data.length; i<len; i++) {
      data[i].event.type = data[i].ref; // <-- Error Occurs here: Cannot set property 'type' of undefined
      data[i].save()
    }
  })

Would love to get some insight. Any help is appreciated!

Upvotes: 1

Views: 528

Answers (1)

robertklep
robertklep

Reputation: 203231

The property type has a special meaning in Mongoose.

If you want to use it as a property name in your schema you need to tell Mongoose to not treat as special:

var schema = new Schema({ 
  ref   : String,
  event : {
    name : String,
    data : mongoose.Schema.Types.Mixed,
    type : String,
  }
}, { typeKey : '$type' });

More info here;

Upvotes: 1

Related Questions