From 7f761355213399fad9aff60ddd9a80f041d8d93e Mon Sep 17 00:00:00 2001 From: Phillip Lassen Date: Wed, 29 Mar 2023 17:38:56 +0200 Subject: [PATCH] fix(docs): mongodb@5 (#213) * fix(docs): mongodb@5 looking into this merged PR, it seems like you are using mongodb v5.x.x already and callbacks are not working anymore. * replace reply.send with return Co-authored-by: Manuel Spigolon * replace reply.send with return Co-authored-by: Manuel Spigolon * rm reply.send --------- Co-authored-by: Manuel Spigolon --- README.md | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 1e8fe87..7c78e32 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ Fastify MongoDB connection plugin; with this you can share the same MongoDB conn Under the hood the official [MongoDB](https://github.com/mongodb/node-mongodb-native) driver is used, the options that you pass to `register` will be passed to the Mongo client. -The `mongodb` driver is v4.x.x. +The `mongodb` driver is v5.x.x. If you do not provide the client by yourself (see below), the URL option is *required*. @@ -32,19 +32,18 @@ fastify.register(require('@fastify/mongodb'), { url: 'mongodb://mongo/mydb' }) -fastify.get('/user/:id', function (req, reply) { +fastify.get('/user/:id', async function (req, reply) { // Or this.mongo.client.db('mydb').collection('users') const users = this.mongo.db.collection('users') // if the id is an ObjectId format, you need to create a new ObjectId const id = this.mongo.ObjectId(req.params.id) - users.findOne({ id }, (err, user) => { - if (err) { - reply.send(err) - return - } - reply.send(user) - }) + try { + const user = await users.findOne({ id }) + return user + } catch (err) { + return err + } }) fastify.listen({ port: 3000 }, err => {