Search code examples
node.jsmongodbmongoose

TypeError: Cannot use 'in' operator to search for 'pluralization' in undefined


I'm trying to achieve inheritance using the discriminator, as shown in the Mongoose API documentation. However, I keep getting the following error:

C:\Code\project\node_modules\mongoose\lib\index.js:364 if (!('pluralization' in schema.options)) schema.options.pluralization = thi
^
TypeError: Cannot use 'in' operator to search for 'pluralization' in undefined at Mongoose.model (C:\Code\project\node_modules\mongoose\lib\index.js:364:34)

Here's the code that causes the error above; my attempt to extend the mongoose Schema class to make my base schema:

var util = require('util');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

function ResourceSchema() {
  Schema.apply(this, arguments);

  this.add({
    title: String
  });
}
util.inherits(ResourceSchema, Schema);

module.exports = mongoose.model('Resource', ResourceSchema);

I have also tried setting the collection name in the last line, but that didn't help.

module.exports = mongoose.model('Resource', ResourceSchema, 'resources');

Solution

  • You're trying to create a model off a schema class, not a schema instance.

    Use this instead:

    module.exports = mongoose.model('Resource', new ResourceSchema());
    

    This is analogous to how you normally create a model:

    var schema = new Schema({ ... }); // or, in your case, ResourceSchema
    var model  = mongoose.model('Model', schema);