Utilize interface as a field type within a mongoose Schema

I am currently working with typescript and mongoose. I have defined an interface like this:

interface Task {
  taskid: Boolean;
  description: Boolean; 
}

My goal is to create a schema where one of the fields contains an array of Tasks:

const employeeSchema = new Schema({
  _id: { type: String, required: true }
  name: { type: String }
  tasks: [Task]
})

However, I encounter an error stating 'Task' only refers to a type, but is being used as a value here. How can I resolve this issue?

Answer №1

According to the official Mongoose documentation:

Mongoose has support for arrays of SchemaTypes and arrays of subdocuments. Primitive arrays are referred to as arrays of SchemaTypes, while arrays of subdocuments are known as document arrays.

If you wish for your workerSchema to include a jobs property that adheres to your Job interface, you can achieve this by:

interface Job {
    jobid: Boolean;
    title: Boolean;
  }

const JobSchema = new Schema<Job>({
  jobid: {
    type: Boolean,
    required: true
  },
  title: {
    type: String,
    required: true
  }
});

const workerSchema = new Schema({
  _id: { type: String, required: true },
  first_name: { type: String },
  jobs: [JobSchema]
});

Answer №2

const employeeSchema = new Schema({
  _id: { type: String required: true }
  first_name: { type: String }
  roles: {type:[Role]}
})

In the absence of work, opt for using a class rather than an interface.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unusual class title following npm packaging

Currently, I am working on developing a Vue 3 library with TypeScript. We are using Rollup for bundling the library. Everything works as expected within the library itself. However, after packing and installing it in another application, we noticed that th ...

Closures are like the "use" keyword in PHP or the capture list in C++, but they play a similar role in JavaScript and other transpiler languages

PHP has a useful feature with the use keyword, which allows for the usage of 'external' variables in closures. For example: $tax = 10; $totalPrice = function ($quantity, $price) use ($tax){ //mandatory 'use' return ($price * $quan ...

"Although the Set-cookie is present in the response header, it is not being properly

I developed a GraphQL server using apollo-server-express, and it is currently running on localhost:4000. Upon sending a query from GraphQL playground, the response includes a set-cookie in the header: response header However, when checking the storage &g ...

Unique Version: Some effective tips for utilizing a fork of type definition such as @types

Currently, I am utilizing Typescript 2.0 along with @types and the experience has been quite positive. Thanks to @types, we can easily leverage type definitions by simply installing the package via npm. Surprisingly, I have not delved into how it actually ...

Angular: implementing a service for conditional module imports

Currently, I have a service that is responsible for loading a list of modules: @Injectable() export class MyService { public allowedModules: any = this.modulesFilter(); constructor() { } public modulesFilter() { const testPef = true; co ...

Retrieve values of properties from an array

How can I retrieve property values from an array? const d = [{id: 'Cat'}, {id: 'Dog'}] type ids = ??? //place code here, type should be 'Cat' | 'Dog' (It would also be acceptable if it creates a const enum) ...

I am unable to locate the type definition file for 'core-js' at the moment

Currently, I am in the process of developing an application using angular2 along with angular-cli. Surprisingly, angular-in-memory-web-api was not included by default. In order to rectify this, I took the initiative to search for it and manually added the ...

Can the ElasticSearch standard Node client be considered secure for integration with cloud functions?

When working with my Typescript cloud functions on GCP, I have been making direct HTTP requests to an ElasticSearch node. However, as my project expands, I am considering switching to the official '@elastic/elasticsearch' package for added conven ...

Retrieve various data types through a function's optional parameter using TypeScript

Creating a custom usePromise function I have a requirement to create my own usePromise implementation. // if with filterKey(e.g `K=list`), fileNodes's type should be `FileNode` (i.e. T[K]) const [fileNodes, isOk] = usePromise( () => { ...

What is the correct way to define functions within an object using Typescript in this situation?

Currently in the process of converting a JavaScript project to TypeScript, I encountered this error message (utilizing urql): A function whose declared type is neither 'void' nor 'any' must return a value. ts(2355) on line: playerCrea ...

Tips for customizing the list of components and attributes for each component in the Angular Form.io builder

I have successfully integrated form.io with Angular 10. After creating a demo project using form.io in the Angular CLI, I was able to develop a custom component and customize the editForm for it. import { Injector } from '@angular/core'; import ...

Locate a subdocument by its unique identifier using the value in the main document

Suppose I have a document with the following structure: { selectedId: ObjectId("57b5fb2d7b41dde99009bc75"), children: [ {_id: ObjectId("57b5fb2d7b41dde99009bc75"), val: 10}, {_id: ObjectId("57b5fb2d7b41dde99009bc75"), val: 20}, ...

Issue arises when fastify/websocket is being used and an argument of type '{ websocket: boolean; }' is not compatible or able to be assigned to a parameter

I am facing an issue with my new project that involves fastify and Typescript. The error I am encountering is as follows: Argument of type '{ websocket: boolean; }' is not assignable to parameter of type 'RouteShorthandOptions ...ts(2345) B ...

Arranging a collection of objects in alphabetical order

My current challenge involves sorting an array of objects alphabetically, and to simplify things, I have provided the example below. In my TypeScript code, I utilize splice to add and remove items from the object array. Array cars = [{ id: 1, ...

A guide on retrieving bytecode from a specific PDF using Angular

Can anyone help me with extracting the bytecode from a selected PDF file to save it in my database? I keep encountering an error stating that my byte is undefined. Could someone please review my code and identify what might be causing this issue? I attemp ...

The addition of types/cors in Express Typescript causes my POSTMAN request to hang indefinitely

I am experiencing an issue with my React web app and Express TypeScript backend. Previously, my POST request was functioning well, but now it seems to hang indefinitely on Postman without returning any errors. issueController.ts import { RequestHandler } ...

Creating nested namespaces with interfaces in Typescript type definitions

In my Javascript project, I am trying to define typing for a specific structure. Consider the following simplified example: a | + A.js + b | + B.js Here we have a folder 'a', and inside it there is another folder 'b'. My goal is t ...

Error encountered when attempting to populate nested fields in Mongoose

Recently, I encountered an error while trying to add comments to my posts by using nested populate for mongoose. Initially, everything was working fine when I only pre-populated user data. However, as soon as I implemented nested populate, I started receiv ...

Using T and null for useRef in React is now supported through method overloading

The React type definition for useRef includes function overloading for both T|null and T: function useRef<T>(initialValue: T): MutableRefObject<T>; // convenience overload for refs given as a ref prop as they typically start with a null ...

Access the plugin object from a Vue.js 2 component using typescript

I devised a plugin object to handle the regular expressions used in my application in a more global manner. Here's an example of how it looks: import Vue from "vue"; Vue.prototype.$regex = { //isEmail function implementation goes here } ...