Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Accessing properties of user document from mongodb , mongoose, and typescript

I m trying to understand why I cannot access certain properties from a user doc. When querying the DB for a user doc, I would like to access its properties.

My User model:

import mongoose from 'mongoose';

export interface IUser extends mongoose.Document {
    email: string;
    password: string;
}

const UserSchema = new mongoose.Schema({
    email: { type: String, required: true, unique: true },
    password: { type: String, required: true },
});

export default mongoose.model<IUser>('User', UserSchema);

The query:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const user = User.findById(payload.sub);
const { email } = user;

This is the typescript error I get:

Property 'email' does not exist on type 'Query<(IUser & { _id: ObjectId; }) | null, IUser & { _id: ObjectId; }, {}, IUser>'.

I fail to understand why I get this error. I also can’t seem to access the _id property.

>Solution :

Querying a database is an asynchronous process. Mongoose will actually not return a Promise directly, but its own class that extends Promise. However, you can still use await to wait for it to resolve:

const user = await User.findById(payload.sub);

if (!user) { /* ??? */ } // no user found

const { email } = user;

You should also check if the user exists, since this method can also return null if no such user was found.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading