Using toJSON() and _id with Mongoose #12837
Unanswered
carrickkv2
asked this question in
Q&A
Replies: 1 comment
-
The below script compiles with Mongoose 6.8.2, try this out: import mongoose from 'mongoose';
export interface UserInterface {
email: string;
name: string;
password: string;
createdAt?: Date;
updatedAt?: Date;
}
export interface UserMethods {
comparePassword(candidatePassword: string): Promise<boolean>;
}
// Create a schema
const userSchema = new mongoose.Schema<UserInterface>(
{
email: { type: String, required: true, unique: true },
name: { type: String, required: true },
password: { type: String, required: true },
},
{
timestamps: true, // Set the date field for a schema.
}
);
type UserModel = mongoose.Model<UserInterface, {}, UserMethods>;
const UserModel = mongoose.model<UserInterface, UserModel>('User', userSchema);
const user = new UserModel({ email: 'test', name: 'test', password: 'test' });
const id: mongoose.Types.ObjectId = user.toJSON()._id; |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
With the old versions of mongoose, we could do something like this
On the documentation page, this is discouraged as it hurts performance.
So I followed the new advice by doing something like this.
Unfortunately, if I try to access the default _id field and the toJSON() method, the ts compiler gives me an error.
Property 'toJSON' does not exist on type 'UserInterface'.ts(2339)
Property '_id' does not exist on type
For clarification, this is one of the functions I use toJSON() in.
Since I can't extend the default document, I'm here to ask what I can do to access these fields and methods. I have read the documentation and looked at the code examples but so far I've seen nothing which can help me. Thanks
Beta Was this translation helpful? Give feedback.
All reactions