Automattic / Automattic/mongoose
Deduced type of an array in a schema is plain array instead of mongoose array.
- Dominant language
- JavaScript
- Stars
- 27.5k
- Forks
- 4k
- Avg merge
- 2d 7h
- Merged PRs (30d)
- 35
Description
### Prerequisites
- [x] I have written a descriptive issue title
### Mongoose version
8.6.2
### Node.js version
20.18.0
### MongoDB version
7.0.14
### Operating system
Windows
### Operating system version (i.e. 20.04, 11.3, 10)
10.0.22631
### Issue
Here is simple example of schema in mongoose:
```typescript
const ExampleSchema = new Schema(
{
names: [
{
type: String,
},
],
},
{
methods: {
addToNames: async function (name: string) {
// this.updateOne() // accessible
this.names.addToSet(name); // Property 'addToSet' does not exist on type 'string[]'. [2339]
},
},
},
);
```
`this` object in a methods is a hydrated document, however array deduced not as mongoose array but as plain array instead. Example demonstrates this issue by trying to use `addToSet` method of a mongoose array, but getting type error.
Same issue can be depicted with this example:
```typescript
type IExampleDocument = HydratedDocumentFromSchema;
const Example = model("example", ExampleSchema);
const example = await Example.create({ names: ["hello"] });
example.names.addToSet("example"); // Property 'addToSet' does not exist on type 'string[]'. [2339]
```
I have pretty vague understanding of how schemas in typescript should be properly defined, I've read that we can provide interfaces ourselves by using template parameters of `model` and `Schema` however it essentially produces a duplication in a boilerplate types and defies already defined principles of deduction established with `HydratedDocumentFromSchema`, `InferSchemaType` and other typescript helper functions.
Contributor guide
Research direction
Start by reproducing the TypeScript errors in the two schema examples using Mongoose 8.6.2, Node.js 20.18.0, and MongoDB 7.0.14. Read the type paths exposed by HydratedDocumentFromSchema and InferSchemaType, then verify that the inferred hydrated array exposes addToSet while retaining the existing schema deduction behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- mongodb, node.js, typescript
- Domain
- databases
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 48/100