mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

mongoose.model.ModelName disrupts types

Open Arctomachine opened this issue 1 year ago • 2 comments

Prerequisites

  • [X] I have written a descriptive issue title

Mongoose version

8.5.1

Node.js version

20.12.2

MongoDB version

4.4.5

Operating system

None

Operating system version (i.e. 20.04, 11.3, 10)

No response

Issue

Problem: if I include mongoose.models.User into export, all types of User queries turn into any. If I remove this line and only export model creation, then typescript picks up correct types. But then I get "cannot overwrite once compiled" errors. I use this because https://stackoverflow.com/questions/19051041/cannot-overwrite-model-once-compiled-mongoose here it is one of suggested solutions, the simplest and it works. But breaks types.

export const User =
	mongoose.models.User || // this line
	mongoose.model(
		'User',
		new mongoose.Schema({
			email: {
				type: String,
				required: true,
				unique: true,
			},
			password: String,
		}),
	)

Arctomachine avatar Jul 29 '24 14:07 Arctomachine