【发布时间】: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;
【问题讨论】: