Closed nikzanda closed 5 days ago
import {
Schema,
connection,
connect,
Model,
model,
SchemaOptions,
SchemaTypes,
} from 'mongoose';
export interface IUser {
name: string;
createdAt: Date;
updatedAt: Date;
}
export interface IUserVirtuals {
id: string;
}
type UserModelType = Model<IUser, {}, {}, IUserVirtuals>;
export type UserInstance = InstanceType<UserModelType>;
const options: SchemaOptions<IUser> = {
timestamps: true,
optimisticConcurrency: true,
};
const userSchema = new Schema<IUser, UserModelType>(
{
name: {
type: SchemaTypes.String,
required: true,
trim: true,
},
},
options
);
const User = model<IUser, UserModelType>('User', userSchema);
async function run() {
await connect('mongodb://localhost:27017');
await connection.dropDatabase();
await User.create({
name: 'John',
});
let user: UserInstance | null = null;
user = await User.findOne().lean();
if (user) {
user.name = 'John Doe'
await user.save();
}
console.log(user);
}
run();
await User.create({ name: 'John', }); let user: UserInstance | null = null; user = await User.findOne().lean(); if (user) { user.name = 'John Doe' await user.save(); } console.log(user);
Sorry, but your code does not work, as the documentation states:
_The lean option tells Mongoose to skip hydrating the result documents. This makes queries faster and less memory intensive, but the result documents are plain old JavaScript objects (POJOs), not Mongoose documents._
Therefore, the save method cannot be called and TypeScript does not report any errors:
As a workaround, you can do user = await User.findOne().lean<IUser>();
. I'm investigating why this issue is happening.
Thank you
Prerequisites
Mongoose version
8.4.4
Node.js version
20.10.0
MongoDB server version
6.0.2
Typescript version (if applicable)
5.4.5
Description
Reproduction link: https://stackblitz.com/edit/stackblitz-starters-9hjjfm?file=src%2Findex.ts
TypeScript should not allow me to assign the result of
await UserModel.findOne().lean();
to the variablelet user: UserInstance | null = null;
in fact, the user.set or user.save instruction results in an error.The code below
![image](https://github.com/Automattic/mongoose/assets/71180446/8c3b6cb8-f5d3-420f-b002-a9fd1090a6b1)
results in an error when executed:
Steps to Reproduce
InstanceType<Model<MyModel>>
;await MyModel.findOne().lean();
.set({ ... })
or.save()
function of the variabile.Expected Behavior
TypeScript should not allow the code to compile