node.jsmongodbcoffeescriptmongoosemongoose-plugins

Adding field in Mongoose plugin gives "TypeError: Invalid value for schema path `CreatedBy.type`"


I'm trying to make a CreatedBy Mongoose plugin, but when trying to use the ObjectId as the field type it gives me ("account" is another defined collection already):

TypeError: Invalid value for schema path `CreatedBy.type`

& here is the plugin code:

mongoose =  require 'mongoose'
module.exports = exports = updatedByPlugin = (schema, options) ->
  schema.add CreatedBy:
    type: mongoose.Schema.Types.ObjectId
    ref: "account"
  schema.pre "save", (next) ->
    @CreatedBy = options.accountId
    next()
    return

  schema.path("CreatedBy").index options.index  if options and options.index
  return

So how I can modify the ref value to make it work?


Solution

  • Well, you won't believe it, but I solved it by adding the CreatedBy field this way

    schema.add CreatedBy:
       ref: "account"
       type: mongoose.Schema.Types.ObjectId
    

    Yes, by just exchanging the 2 lines for ref & type!! . It is weird how exchanging these 2 lines could break the code :| !!!