Skip to content

this: Object is possibly 'undefined #147

@bkawk

Description

@bkawk

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

3.0.0

Plugin version

3.0.0

Node.js version

14.15.4

Operating system

macOS

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

11.5.2

Description

In a TypeScript environment when trying to access this as shown in the docs, inside the route it's always possibly undefined. If I ensure it defined I get `Property 'mongo' does not exist on type 'never'

Steps to Reproduce

I've set up the plugin with

import fp from 'fastify-plugin';
import mongodb from 'fastify-mongodb';

export default fp(async (fastify) => {
  fastify.register(mongodb, {
    url: 'mongodb+srv://dbuser:mypassword@cluster0.otigz.mongodb.net/myapp?retryWrites=true&w=majority',
  });
});

then in the handler, I have

const postJoinHandler = async (
  request: any,
  reply: any
): Promise<{ id: string; name: string }> => {
  try {
    const { username, password } = request.body;
    
    const test = await this.mongo.db.collection('users');
    test.insertOne({
      username,
      password,
    });

    return reply.code(201).send(username);
  } catch (error) {
    request.log.error(error);
    return reply.send(400);
  }
};

if I try to make sure this is not denied with...

    const t = this;
    if (t) {
      const test = t.mongo.client.db('mydb').collection('users');
      test.insertOne({
        username,
        password,
      });
      console.log(test);
    }

I get `Property 'mongo' does not exist on type 'never'

in the router I have

import { FastifyPluginAsync } from 'fastify';
import { postJoinSchema, postLoginSchema } from '../schemas/auth';

const auth: FastifyPluginAsync = async (fastify): Promise<void> => {
  fastify.post('/auth/join', postJoinSchema);
  fastify.post('/auth/login', postLoginSchema);
};

export default auth;

Full example here https://github.com/bkawk/fastify-swagger/blob/mongodb/src/handlers/auth.ts#L9-L18

Expected Behavior

I expect to be able to write to the database by following the examples in the readme

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions