Home > Software engineering >  Accessing properties of user document from mongodb , mongoose, and typescript
Accessing properties of user document from mongodb , mongoose, and typescript

Time:10-31

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:

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.

CodePudding user response:

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.

  • Related