如何通过插件fastify-mongodb访问mongodb



我的插件看起来像

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;

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 {}
}
};

最新更新