【问题标题】:How to access mongodb via the plugin fastify-mongodb如何通过插件 fastify-mongodb 访问 mongodb
【发布时间】:2021-10-08 23:34:05
【问题描述】:

我的插件看起来像

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

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

我的处理程序看起来像

const postJoinHandler = async (
  request: any,
  reply: any
): Promise<{ id: string; name: string }> => {
  try {
    const { username, password } = request.body; 

    const test = await reply.mongo.db.users.insertOne({
      username,
      password,
    });
    console.log(test);

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

期望它将用户名和密码插入到名为 users 的集合中,但它没有?错误是Cannot read property 'db' of undefined

我也试过

reply.mongodb.users.insertOne({...

    const test = await request.mongodb.collection('users');

    test.insertOne({
      username,
      password,
    });
    console.log(test);

const test = await this.mongo.db.collection('users'); //<= Object is possibly 'undefined'

路线看起来像

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;

【问题讨论】:

    标签: mongodb fastify


    【解决方案1】:

    mongo 装饰器附加到 fastify 实例,而不是 requestreply 对象。

    您应该将处理程序移动到路由文件中并读取fastify.mongo 或使用命名函数作为处理程序。

    在后一种情况下,处理程序将this 绑定到fastify 实例。

    async function postJoinHandler (
      request,
      reply
    ) {
      try {
        const { username, password } = request.body; 
    
        const test = await this.mongo.db.users.insertOne({
          username,
          password,
        });
        console.log(test);
    
        reply.code(201)
        return username
      } catch (error) {
        request.log.error(error);
        reply.code(400);
        return {}
      }
    };
    

    【讨论】:

    • 我现在得到这个错误'error TS2683:'this' 隐含类型'any',因为它没有类型注释。'和 'this' 的外部值被此容器遮蔽。'
    • 这是一个 TS 问题。我不是 TypeScript 开发人员
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 2011-01-09
    • 2021-07-21
    • 1970-01-01
    相关资源
    最近更新 更多