arraystypescriptmongodbmongoosetypes

Error while making a schema with mongoose


I am exepriencing an issue with my schema I made with mongoose in Typescript. This is the current code:

import { Schema, model } from "mongoose";

interface ISchema {
  guildId: string;
  counters: string[];
  uniqueCounters: string[];
}

const schema = new Schema<ISchema>({
  guildId: {
    type: String,
    required: true,
  },
  counters: {
    type: Array,
    default: [],
  },
  uniqueCounters: {
    type: Array,
    default: [],
  },
});

export default model("Counting", schema);

But my code editor says there is an issue with counters and uniqueCounters:

Type '{ type: ArrayConstructor; default: never[]; }' is not assignable to type 'SchemaDefinitionProperty<string[], ISchema> | undefined'.
  Types of property 'type' are incompatible.
    Type 'ArrayConstructor' is not assignable to type 'typeof Mixed | AnyArray<StringSchemaDefinition> | AnyArray<SchemaTypeOptions<string, ISchema>> | undefined'.
      Type 'ArrayConstructor' is missing the following properties from type 'typeof Mixed': schemaName, cast, checkRequired, set, getts(2322)

And since im quite new to TS, I can't really tell what is going wrong. Is there someone that knows how to fix this issue? Thanks :)


Solution

  • Here the problem seems to be that you want to specify an array of string but in the schema you just pass in the Array constructor, that's why you see the never[] type. You need to specify that it is an array of string in the schema, I would do something like this:

    import { Schema, model } from "mongoose";
    
    interface ISchema {
      guildId: string;
      counters: string[];
      uniqueCounters: string[];
    }
    
    const schema = new Schema<ISchema>({
      guildId: {
        type: String,
        required: true,
      },
      counters: {
        type: [String],
        default: [],
      },
      uniqueCounters: {
        type: [String],
        default: [],
      },
    });
    
    export default model("Counting", schema);
    

    You can find some documentation on the subject here: https://mongoosejs.com/docs/schematypes.html#arrays