Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 🙂

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading