Giter Site home page Giter Site logo

fastify-mongodb's Introduction

CI Package Manager CI Web SIte js-standard-style CII Best Practices

NPM version NPM downloads Security Responsible Disclosure Discord Contribute with Gitpod Open Collective backers and sponsors


An efficient server implies a lower cost of the infrastructure, a better responsiveness under load and happy users. How can you efficiently handle the resources of your server, knowing that you are serving the highest number of requests as possible, without sacrificing security validations and handy development?

Enter Fastify. Fastify is a web framework highly focused on providing the best developer experience with the least overhead and a powerful plugin architecture. It is inspired by Hapi and Express and as far as we know, it is one of the fastest web frameworks in town.

The main branch refers to the Fastify v4 release. Check out the v3.x branch for v3.

Table of Contents

Quick start

Create a folder and make it your current working directory:

mkdir my-app
cd my-app

Generate a fastify project with npm init:

npm init fastify

Install dependencies:

npm i

To start the app in dev mode:

npm run dev

For production mode:

npm start

Under the hood npm init downloads and runs Fastify Create, which in turn uses the generate functionality of Fastify CLI.

Install

To install Fastify in an existing project as a dependency:

Install with npm:

npm i fastify

Install with yarn:

yarn add fastify

Example

// Require the framework and instantiate it

// ESM
import Fastify from 'fastify'
const fastify = Fastify({
  logger: true
})
// CommonJs
const fastify = require('fastify')({
  logger: true
})

// Declare a route
fastify.get('/', (request, reply) => {
  reply.send({ hello: 'world' })
})

// Run the server!
fastify.listen({ port: 3000 }, (err, address) => {
  if (err) throw err
  // Server is now listening on ${address}
})

with async-await:

// ESM
import Fastify from 'fastify'
const fastify = Fastify({
  logger: true
})
// CommonJs
const fastify = require('fastify')({
  logger: true
})

fastify.get('/', async (request, reply) => {
  reply.type('application/json').code(200)
  return { hello: 'world' }
})

fastify.listen({ port: 3000 }, (err, address) => {
  if (err) throw err
  // Server is now listening on ${address}
})

Do you want to know more? Head to the Getting Started.

Note

.listen binds to the local host, localhost, interface by default (127.0.0.1 or ::1, depending on the operating system configuration). If you are running Fastify in a container (Docker, GCP, etc.), you may need to bind to 0.0.0.0. Be careful when deciding to listen on all interfaces; it comes with inherent security risks. See the documentation for more information.

Core features

  • Highly performant: as far as we know, Fastify is one of the fastest web frameworks in town, depending on the code complexity we can serve up to 76+ thousand requests per second.
  • Extensible: Fastify is fully extensible via its hooks, plugins and decorators.
  • Schema based: even if it is not mandatory we recommend to use JSON Schema to validate your routes and serialize your outputs, internally Fastify compiles the schema in a highly performant function.
  • Logging: logs are extremely important but are costly; we chose the best logger to almost remove this cost, Pino!
  • Developer friendly: the framework is built to be very expressive and help the developer in their daily use, without sacrificing performance and security.

Benchmarks

Machine: EX41S-SSD, Intel Core i7, 4Ghz, 64GB RAM, 4C/8T, SSD.

Method:: autocannon -c 100 -d 40 -p 10 localhost:3000 * 2, taking the second average

Framework Version Router? Requests/sec
Express 4.17.3 14,200
hapi 20.2.1 42,284
Restify 8.6.1 50,363
Koa 2.13.0 54,272
Fastify 4.0.0 77,193
-
http.Server 16.14.2 74,513

Benchmarks taken using https://github.com/fastify/benchmarks. This is a synthetic, "hello world" benchmark that aims to evaluate the framework overhead. The overhead that each framework has on your application depends on your application, you should always benchmark if performance matters to you.

Documentation

中文文档地址

Ecosystem

  • Core - Core plugins maintained by the Fastify team.
  • Community - Community supported plugins.
  • Live Examples - Multirepo with a broad set of real working examples.
  • Discord - Join our discord server and chat with the maintainers.

Support

Please visit Fastify help to view prior support issues and to ask new support questions.

Contributing

Whether reporting bugs, discussing improvements and new ideas or writing code, we welcome contributions from anyone and everyone. Please read the CONTRIBUTING guidelines before submitting pull requests.

Team

Fastify is the result of the work of a great community. Team members are listed in alphabetical order.

Lead Maintainers:

Fastify Core team

Fastify Plugins team

Great Contributors

Great contributors on a specific area in the Fastify ecosystem will be invited to join this group by Lead Maintainers.

Past Collaborators

Hosted by

We are a At-Large Project in the OpenJS Foundation.

Sponsors

Support this project by becoming a SPONSOR! Fastify has an Open Collective page where we accept and manage financial contributions.

Acknowledgements

This project is kindly sponsored by:

Past Sponsors:

This list includes all companies that support one or more of the team members in the maintenance of this project.

License

Licensed under MIT.

For your convenience, here is a list of all the licenses of our production dependencies:

  • MIT
  • ISC
  • BSD-3-Clause
  • BSD-2-Clause

fastify-mongodb's People

Contributors

allevo avatar cemremengu avatar climba03003 avatar delvedor avatar dependabot-preview[bot] avatar dependabot[bot] avatar eomm avatar fdawgs avatar frikille avatar github-actions[bot] avatar greenkeeper[bot] avatar ishibi avatar johnwebbcole avatar jorisdugue avatar jsumners avatar lemonclown avatar lependu avatar mcollina avatar megaxayda avatar mihaur avatar mirchow avatar pacodu avatar pip77 avatar salmanm avatar sebdeckers avatar skellla avatar uzlopak avatar wedgwood avatar zekth avatar zhaoyao91 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fastify-mongodb's Issues

fastify-mongodb is "eating" errors on register

Prerequisites

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

Fastify version

3.20.2

Plugin version

4.1.0

Node.js version

4.1.0

Operating system

Linux

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

Manjaro 21.1.1

Description

When there is some error on fastify-mongodb configuration (uri error), the error is not throw and the fastify-autoload does not load the paths.

Steps to Reproduce

structure:

src/app.js
src/services/health.js

app.js

const fastify = require('fastify')({ logger: true })
const path = require('path')

//HERE: I 'forget' the configuration...
//NOTICE: To see the autoloader works, just comment this line:
fastify.register(require('fastify-mongodb'))

//HERE: this was registered :)
fastify.get('/hello', async (request, reply) => {
  return { hello: 'world' }
})
//HERE: this load no file :(
fastify.register(require('fastify-autoload'), {
  dir: path.join(__dirname, 'services'),
  options: { prefix: '/api' },
  ignorePattern: /.*(test|spec).js/
})
fastify.ready(() => {
  console.log('Routes\n' + fastify.printRoutes())
})

const start = async () => {
  try {
    await fastify.listen(3000)
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

health.js

'use strict'

module.exports = async function (fastify, opts) {
  fastify.get('/', async function (request, reply) {
    try {
      let stats = await fastify.mongo.db.stats()
      if (stats.ok) {
        reply.send({ message: 'OK' })
      } else {
        reply.status(500).send({ message: 'NOK' })
      }
    } catch (e) {
      reply.status(500).send({ message: 'NOK', error: e.message })
    }
  })
}

module.exports.autoPrefix = '/health'

start the server node src/app.js and the output will be:

$ node src/app.js 
Routes
└── /hello (GET)

{"level":30,"time":1630624706482,"pid":10021,"hostname":"barenko-virtualbox","msg":"Server listening at http://127.0.0.1:3000"}

Expected Behavior

$ node src/app.js 
Routes
└── /
    ├── hello (GET)
    └── api
        ├── /health (GET)
             └── / (GET)


{"level":30,"time":1630624488203,"pid":9675,"hostname":"barenko-virtualbox","msg":"Server listening at http://127.0.0.1:3000"}

An in-range update of mongodb is breaking the build 🚨

The dependency mongodb was updated from 3.1.4 to 3.1.5.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

mongodb is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Commits

The new version differs by 9 commits.

  • 51f94b8 chore(release): 3.1.5
  • 805d58a feat(core): bump core to v3.1.4
  • 3b725ef fix(utils): only set retryWrites to true for valid operations
  • f93a8c3 fix(cursor): allow $meta based sort when passing an array to sort()
  • bd80fb2 doc(kerberos): fix typo in Kerberos connection section, and url
  • 3c9ef0d docs(collection): remove unnecessary information for estimatedDocumentCount
  • 6d6cb2e docs(HISTORY): fixed typos
  • cb4888d chore(lock): update npm lock file
  • 7d6dd0c chore(yarn): remove yarn lock file for travis runs

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

this.mongo does not exist

🐛 Bug Report

I did everything depending on the tutorial, but this.mongo does not exist

To Reproduce

Steps to reproduce the behavior:

// /app.js
const path = require('path');
const config = require('config');
const fastify = require('fastify');
const autoload = require('fastify-autoload');
const mongodb = require('fastify-mongodb');

const app = fastify({ logger: true });

app.register(mongodb, {
	url: config.get('db.mongo.uri'),
});

app.register(autoload, {
	dir: path.join(__dirname, 'plugins'),
});

app.listen(config.get('port'));

// /plugins/stats/index.js
module.exports = function (fastify, opts, next) {
	fastify.get('/get', async (request, res) => {
		console.log(this.mongo);
		res.send({ hello: 'world' });
	});

	next();
};

module.exports.autoPrefix = '/stats';

Expected behavior

A clear and concise description of what you expected to happen.

// this.mongo is undefined

Your Environment

  • node version: 12
  • fastify version: >=2.0.0
  • os: Windows
  • any other relevant information

Pass variable to regex fails

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.29.0

Plugin version

5.0.0

Node.js version

16.15.0

Operating system

Windows

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

Windows 10 Home Version 22H2 Build 19045.2846

Description

  1. If I hard code value to regex expression (starting with) function returns expexted data
async function  policyclifton(yearsearch,policycodesearch) {
     return  policycollection.find({
   "EffectiveYear" :yearsearch,  $and : [ { "Policy Number" : /^CA.*/i } ]
       }).toArray()
 }

if I pass a vairable to regex function fails to return data

 async function  policyclifton(yearsearch,policycodesearch) {
      return  policycollection.find({
     "EffectiveYear" :yearsearch, 
      $and : [ { "Policy Number" :  "/^" + policycodesearch + "/i" } ] 
     }).toArray() 
   }

Collection item

{
    "_id" : ObjectId("6451803e3a7ff068cda2ebdf"),
    "Policy Number" : "CA 6675503",
    "EffectiveYear" : 2020
}

Steps to Reproduce

given above

Expected Behavior

variable pass to regex returns data

An in-range update of @types/mongodb is breaking the build 🚨

The devDependency @types/mongodb was updated from 3.2.1 to 3.2.2.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/mongodb is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Consider re-exporting some (all?) types from mongodb

Prerequisites

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

🚀 Feature Proposal

Re-export some (all?) types from mongodb package.

Motivation

Currently there's no way of using most of the types included in this plugin's mongodb dependency as they're not re-exported from the plugins type declaration files (I think only ObjectId is being re-exported), to make use of those types it is necessary to install the mongodb package as a dev dependency of the whole project.
I want to write a helper function to parse some queryString parameters and create a mongodb query object, currently the only way to make this type safe is to add mongodb as a dev dependency of the project and import the types from it, but this makes the project end up with two installations of the module (maybe even different!).

Example

import type { Filter } from '@fastify/mongodb' <--- This should be possible
// import type { Filter } from 'mongodb' <--- This shouln't be necessary

function filterParser(obj?: FilterSchema) {
  const filter: Filter<Event> & Record<string, unknown> = {
    active: true
  }
  Object.entries(obj ?? {}).forEach(([k, v]) => {
    switch (k) {
      case 'title':
      case 'summary':
      case 'description':
        if (typeof v === 'string') {
          filter[k] = { $regex: v, $options: 'i' }
        }
        break
        ...

Problem about #46

I found a problem about #46

  • there is a warn log since this plugin pass the all options to underlining mongo driver, but it does not accept it
  • this plugin only pass database and name to the decorate function, so it doesn't get the forceClose option.

I will send a PR to fix

MongoError: Cannot use a session that has ended (in tap test suites)

In case someone ran into this

Fresh install of fastify-mongodb installed [email protected]. Now any tap test suite break with "MongoError: Cannot use a session that has ended", even without mongo operations. Last working version seamed to be [email protected] - pinnig to it by

 "resolutions": {
    "mongodb": "3.4.1"
  }

resolves... as a quick fix. Root-Cause will probably be on mongodb's side. Wanted to share my experience for anyone running into same issue.

To Reproduce

I wanted to setup demo repo with an excerpt of my breaking setup. Guess what: It works! I will take some time to figure out

Expected behavior

I've seen plenty of issues with mongodb driver before, like you did with greenkeeper upgrades. I'd expect maintainers at mongo to not break on minor upgrades any more - but this is out of scope of this report... just wanted to provide a quick workaround fix... will do my best to reproduce though. Thanks!

Your Environment

  • node version: 12.x
  • fastify version: >=2.0.0
  • os: Mac & Linux

Typescript: object is possibly undefined

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.25.3

Plugin version

4.1.1

Node.js version

16.13.1

Operating system

macOS

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

12.1

Description

When trying to call fastify.mongo.db.collection, I get a warning from TS telling me db is possibly undefined
This forces me to override the type in every db call I make in the entire app

Steps to Reproduce

Hi, i'm using your package with typescript 4.5.4 configured with scrict mode
My registering:

  instance.register(MongoDb, {
    forceClose: true,
    database: instance.config.MONGO_DB_NAME,
    url: instance.config.MONGO_ENDPOINT,
  })

I checked types and indeed, db has been declared with db?: DB

Expected Behavior

As stated by the doc, if we have a database string in plugin options or a mongo url containing the database name, you are sure to have a db property on fastify.mongo, therefore we should not need to override types everywhere in the app

Throw fastify-mongodb error instead of avvio error

Prerequisites

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

Fastify version

3.20.0

Plugin version

4.0.0

Node.js version

15.13.0

Operating system

Linux

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

20.04

Description

I am trying to connecting to mongodb with url like usual. I wonder why its timeout and especially by this module "avvio". Turns out i forget to whitelist my ip address and thats why i was rejected. But, i think would be good for fastify-mongodb to catch this timeout error when connecting db

rror: ERR_AVVIO_PLUGIN_TIMEOUT: plugin did not start in time: /home/wwww/product/node_modules/fastify-mongodb/index.js. You may have forgotten to call 'done' function or to resolve a Promise at Timeout._onTimeout (/home/wwwww/product/node_modules/avvio/plugin.js:123:19) at listOnTimeout (node:internal/timers:557:17) at processTimers (node:internal/timers:500:7) { code: 'ERR_AVVIO_PLUGIN_TIMEOUT', fn: <ref *1> [Function: fastifyMongodb] { default: [Circular *1], fastifyMongodb: [Circular *1], [Symbol(skip-override)]: true, [Symbol(fastify.display-name)]: 'fastify-mongodb', [Symbol(plugin-meta)]: { fastify: '>=1.0.0', name: 'fastify-mongodb' } } }

Steps to Reproduce

  1. connect db
  2. timeout
  3. console.log(err) show avvio error

Expected Behavior

Its should be mongodb error but avvio catch it instead

Move MongoDB to peerDependencies

Prerequisites

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

Fastify version

4.14.1

Plugin version

6.2.0

Node.js version

16

Operating system

Windows

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

11

Description

MongoDB should be moved from dependencies to peerDependencies

Expected Behavior

No response

Update MongoDB v5

Prerequisites

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

Issue

No response

find() method returns events

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.27.1

Plugin version

4.1.1

Node.js version

17.3

Operating system

Linux

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

Arch Linux latest

Description

Returns an object with events instead of the actual objects from the database.

Steps to Reproduce

const app = require('fastify')()

app.register(require('fastify-mongodb', options)

app.get('/test', async function(req,res){
    let collection = this.mongo.db.collection('test')
    let result = await collection.find({});

    return res.send(result)
    // {"_events":{},"_eventsCount":0}
})

Expected Behavior

Should return a result with documents, not events.

test tap not ok timeout!

I'm trying to create a fastify plugin for postgresql based on this one and I have this issue when doing test :

Here is the implementation :
screen shot 2017-05-17 at 3 37 21 pm

index.js

'use strict'

const fp = require('fastify-plugin')
const pg = require('pg')

function fastifyPg (fastify, options, next) {
  var client

  if (options.pool) {
    client = new pg.Pool(options.connection)
  } else {
    client = new pg.Client(options.connection)
  }

  client.connect(onConnect)

  function onConnect (err) {
    if (err) return next(err)

    fastify
      .decorate('pg', client)
      .addHook('onClose', close)

    next()
  }
}

function close (fastify, done) {
  fastify.pg.end()
}

module.exports = fp(fastifyPg, '>=0.13.1')

And test :

'use strict'

const t = require('tap')
const test = t.test
const Fastify = require('fastify')
const fastifyPg = require('./index')

test('fastify.pg should exist', t => {
  t.plan(3)

  const fastify = Fastify()

  fastify.register(fastifyPg, {}, err => {
    t.error(err)
  })

  fastify.ready(err => {
    t.error(err)
    t.ok(fastify.pg)

    fastify.close()
  })
})

test('fastify.pg should exist (with config and pool)', t => {
  t.plan(3)

  const fastify = Fastify()

  fastify.register(fastifyPg, {
    pool: true,
    connection: {
      host: 'localhost',
      port: 5432
    }
  }, err => {
    t.error(err)
  })

  fastify.ready(err => {
    t.error(err)
    t.ok(fastify.pg)

    fastify.close()
  })
})

test('fastify.pg should be the postgresql database client', t => {
  t.plan(3)

  const fastify = Fastify()

  fastify.register(fastifyPg, {}, err => {
    t.error(err)
  })

  fastify.ready(err => {
    t.error(err)

    var rollback = (err) => {
      fastify.pg.query('ROLLBACK', () => {
        if (err) {
          t.error(err)
        }
        fastify.close()
      })
    }

    fastify.pg.query('BEGIN', (err, result) => {
      if (err) {
        return rollback(err)
      }
      fastify.pg.query('CREATE TABLE companies (id VARCHAR(9) PRIMARY KEY)', (err, result) => {
        if (err) {
          return rollback(err)
        }
        fastify.pg.query("INSERT INTO companies VALUES('123123123')", (err, result) => {
          if (err) {
            return rollback(err)
          }
          t.equal(1, result.rowCount)
          rollback()
        })
      })
    })
  })
})

When does the database disconnect occur?

const fastify = require('fastify')()

fastify.register(require('fastify-mongodb'), {
  url: 'mongodb://mongo/mydb'
})

fastify.get('/user/:id', function (req, reply) {
  // Or this.mongo.client.db('mydb')
  const db = this.mongo.db
  db.collection('users', onCollection)

  function onCollection (err, col) {
    if (err) return reply.send(err)

    col.findOne({ id: req.params.id }, (err, user) => {
      reply.send(user)
    })
  }
})

fastify.listen(3000, err => {
  if (err) throw err
})

In this code, I did not see db.close to manually shut down the database. I would like to ask what kind of mechanism is fastify-mongodb to handle on the database.

TypeScript Example needed

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

Operating system

macOS

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

11.5.2

Description

The docs do not provide a typescript async example and the use of this causes a number of errors

  1. 'this' implicitly has type 'any' because it does not have a type annotation.
  2. An outer value of 'this' is shadowed by this container.

Steps to Reproduce

const postJoinHandler = async function (  //<==  An outer value of 'this' is shadowed by this container.
  request: any,
  reply: any
): Promise<{ id: string; name: string }> {
  try {
    const { username, password } = request.body;
    const token = await reply.jwtSign({ username, password });
    const users = this.mongo.db.collection('users'); // <== 'this' implicitly has type 'any' because it does not have a type annotation.

    users.insertOne({
      username,
      password,
    });

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

export { postJoinHandler };

Expected Behavior

I expect to be able to use TypeScript and fastify-mongodb

ScaleGrid connection

After updating a production repo to testing repo 1 error is raised when attaching to a scalegrid mongodb database. If I test on local computer with the old setup it connects as designed.
// Paste your code here
Current update
"fastify": "^2.13.1",
"fastify-autoload": "^1.2.2",
"fastify-cli": "^1.5.0",
"fastify-cookie": "^3.6.0",
"fastify-cors": "^3.0.3",
"fastify-favicon": "^2.0.0",
"fastify-jwt": "^1.3.1",
"fastify-mongodb": "^1.0.1",
"fastify-multipart": "^1.0.5",
"fastify-mysql": "^1.0.0",
"fastify-plugin": "^1.6.1",
"fastify-session": "^3.3.0",
"fastify-swagger": "^2.5.1",
Previous versions:
"fastify": "^2.13.1",
"fastify-autoload": "^1.2.2",
"fastify-cli": "^1.5.0",
"fastify-cookie": "^3.6.0",
"fastify-cors": "^3.0.3",
"fastify-favicon": "^2.0.0",
"fastify-jwt": "^1.3.1",
"fastify-mongodb": "^2.0.0",
"fastify-multipart": "^1.0.5",
"fastify-mysql": "^1.0.0",
"fastify-plugin": "^1.6.1",
"fastify-session": "^3.3.0",
"fastify-swagger": "^2.5.1",

Expected behavior

MONGODB_URLmas=mongodb://admin:@SG-Brookbridge-22047.servers.mongodirector.com:48815,SG-Brookbridge-22048.servers.mongodirector.com:48815,SG-Brookbridge-22049.servers.mongodirector.com:48815/admin?replicaSet=RS-Brookbridge-0&ssl=true&databases=mas

.register(require('fastify-mongodb'), useNewUrlParser: true, url: process.env.MONGODB_URLmas, name: 'mas' })
error upon start

002===plugin================fastify mongodb======
(node:45476) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
assert.js:749
    throw newErr;
    ^

AssertionError [ERR_ASSERTION]: ifError got unwanted exception: failed to connect to server [sg-brookbridge-22049.servers.mongodirector.com:48815] on first connect [MongoNetworkError: connection 6 to sg-brookbridge-22049.servers.mongodirector.com:48815 closed]
    at wrap (D:\fastify\mongodonBRMwithFBNew\server.js:111:5)
    at ready.err (D:\fastify\mongodonBRMwithFBNew\node_modules\fastify\lib\server.js:130:31)
    at Object._encapsulateThreeParam (D:\fastify\mongodonBRMwithFBNew\node_modules\avvio\boot.js:450:13)
    at Boot.timeoutCall (D:\fastify\mongodonBRMwithFBNew\node_modules\avvio\boot.js:370:5)
    at Boot.callWithCbOrNextTick (D:\fastify\mongodonBRMwithFBNew\node_modules\avvio\boot.js:351:19)
    at release (D:\fastify\mongodonBRMwithFBNew\node_modules\fastq\queue.js:140:16)
    at Object.resume (D:\fastify\mongodonBRMwithFBNew\node_modules\fastq\queue.js:74:7)
    at Boot.Plugin.loadPlugin.call (D:\fastify\mongodonBRMwithFBNew\node_modules\avvio\boot.js:161:18)
    at toLoad.finish (D:\fastify\mongodonBRMwithFBNew\node_modules\avvio\plugin.js:190:7)
    at done (D:\fastify\mongodonBRMwithFBNew\node_modules\avvio\plugin.js:136:5)
    at Pool.<anonymous> (D:\fastify\mongodonBRMwithFBNew\node_modules\mongodb\lib\core\topologies\server.js:438:11)
    at Pool.emit (events.js:189:13)
    at createConnection (D:\fastify\mongodonBRMwithFBNew\node_modules\mongodb\lib\core\connection\pool.js:561:14)
    at connect (D:\fastify\mongodonBRMwithFBNew\node_modules\mongodb\lib\core\connection\pool.js:1008:9)
    at callback (D:\fastify\mongodonBRMwithFBNew\node_modules\mongodb\lib\core\connection\connect.js:97:5)
    at runCommand (D:\fastify\mongodonBRMwithFBNew\node_modules\mongodb\lib\core\connection\connect.js:124:7)
    at _callback (D:\fastify\mongodonBRMwithFBNew\node_modules\mongodb\lib\core\connection\connect.js:349:5)
    at Connection.errorHandler (D:\fastify\mongodonBRMwithFBNew\node_modules\mongodb\lib\core\connection\connect.js:365:5)
    at Object.onceWrapper (events.js:277:13)
    at Connection.emit (events.js:189:13)
// All other connections work (local, ObjectRocket and mlab)

Your Environment

  • node version: 10.15.3 and tested with 11.10.0
  • fastify version: >=2.0.0
  • os: Windows10

Strange behavior with addHook/preHandler

Hi there !

I found a strange behavior with this plugin & addHook function.
Here is my sample code to reproduce it :

const fastify = require('fastify')();

fastify.register(require('fastify-mongodb'), {
  url: 'mongodb://localhost/tests',
});

fastify.register((instance, options, next) => {

  instance.addHook('preHandler', (req, res, next) => {
    console.log('Plugin preHandler 1');
    next();
  });

  instance.get('/', async (req, res) => {
    return {
      foo: 'bar',
    };
  });

  instance.addHook('preHandler', (req, res, next) => {
    console.log('Plugin preHandler 2');
    next();
  });

  next();
});

fastify.addHook('preHandler', (req, res, next) => {
  console.log('Top preHandler');
  next();
});

fastify.listen(3000);

If i go to http://localhost:3000 my terminal print this :

Top preHandler
Plugin preHandler 1

Plugin preHandler 2 is missing...

If i disable/comment fastify.register(require('fastify-mongodb')), my terminal print this :

Top preHandler
Plugin preHandler 1
Plugin preHandler 2

Did I miss something ?

An in-range update of @types/node is breaking the build 🚨

Version 10.9.1 of @types/node was just published.

Branch Build failing 🚨
Dependency @types/node
Current Version 10.9.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Fastify get route requires options?

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.24.0

Plugin version

No response

Node.js version

16.13.0

Operating system

macOS

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

12.0.1

Description

The Fastify get route may not have a properly overloaded get route, given that it seems we must specify options (which I thought were optional)?

Steps to Reproduce

In the README, there is this route:

fastify.get('/user/:id', function (req, reply) {
...
    })

However, sending a basic curl request gives this error:

victor@Victors-MBP Test3 % curl -X GET http://localhost:3000/user/:id
{"statusCode":500,"error":"Internal Server Error","message":"Argument \"options\" must not be function"}%

An in-range update of mongodb is breaking the build 🚨

The dependency mongodb was updated from 3.3.2 to 3.3.3.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

mongodb is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Commits

The new version differs by 146 commits.

  • f326744 chore(release): 3.3.3
  • 4cdb950 Revert "feat(Update): add the ability to specify a pipeline to an update command (#2017)"
  • 558d4fb test: simply access to required topology directive
  • 8e5391d test: remove deprecated test runner filters
  • 0a98aa4 test: don't throw errors in eachAsync in new test runner
  • ee15ea0 refactor(monitoring): hoist Server constants out of monitor code
  • 8a4de3f test: remove legacy code for no longer existant server bug
  • 7b8dcbf test: remove accidentally committed debug code
  • 33744f5 test: remove duplicate configuration code
  • 3fe378a chore: reenable linting as part of test script
  • 6fc750e chore: remove dependency on mongodb-test-runner
  • 8ccea97 test(es-next): ensure inventory collection is already created
  • c5f1558 test: add configuration for evergreen
  • b6f356d test: close => destroy
  • 6eb2e16 test: check that servers exist before coercing them into an array

There are 146 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

[email protected] is incompatible with newer version of [email protected].

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.28.0

Plugin version

4.0.1

Node.js version

16.13.1

Operating system

Linux

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

20.04

Description

[email protected] is incompatible with newer version of [email protected].

In my case, linter will tell me there is no MongoServerError attribute in MongoDB. Even when we use ts-ignore, we couldn't select thrown MongoServerError instance with if (err instance of MongoServerError)

Steps to Reproduce

This happens when we do not specify which mongodb version to use and yarn/npm will install the latest instead (e.g 4.5.0).

Expected Behavior

No response

(examples) Do not throw in async flows

Hey,
I was just having a look to this plugin and, reading the example, I noticed this:

fastify.register(require('fastify-mongodb'), {
  url: 'mongodb://mongo/db'
}, err => {
  if (err) throw err
})

Throwing in in async flow is an antipattern, it will probably crash your entire process as nobody can catch that exception. While it's just an example, you might want to write a different code to handle the error.

P.S: The same goes in the listen function below.

this: Object is possibly 'undefined

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:[email protected]/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

GCP Deploy using @fastify/mongodb

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.29.0

Plugin version

3.0.1

Node.js version

16.15.0

Operating system

Windows

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

Version 21H1 build19043.1706

Description

I updated repo to lastest version of the following
"mongodb": "^4.6.0"
@fastify/mongodb": "^5.0.0
Locally the connection to scagrid mongo 4.4 works fine.
When I deploy to GCP I get the following error

AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Server selection timed out after 7500 ms
    at wrap (/workspace/server.js:118:5)
    at /workspace/node_modules/fastify/lib/server.js:147:31
    at manageErr (/workspace/node_modules/fastify/fastify.js:505:11)
    at /workspace/node_modules/fastify/fastify.js:494:11
    at Object._encapsulateThreeParam (/workspace/node_modules/avvio/boot.js:551:7)
    at Boot.timeoutCall (/workspace/node_modules/avvio/boot.js:447:5)
    at Boot.callWithCbOrNextTick (/workspace/node_modules/avvio/boot.js:428:19)
    at release (/workspace/node_modules/fastq/queue.js:149:16)
    at Object.resume (/workspace/node_modules/fastq/queue.js:82:7)
    at /workspace/node_modules/avvio/boot.js:167:18
    at Timeout._onTimeout (/workspace/node_modules/mongodb/lib/sdam/topology.js:305:38)
    at listOnTimeout (node:internal/timers:559:17)
    at processTimers (node:internal/timers:502:7) {

All deployements work as expected using scalegrid version mongodb 3.6
with the folliwing
[email protected]
"fastify-mongodb": "^1.0.1",
"fastify": "^2.6.0",
"fastify-plugin": "^1.6.0"

Steps to Reproduce

Update repos to latest versions and use a scalegrid mongodb 4.4 connection
MONGODB_URLtodo=mongodb://admin:@SG-gtz-nano2-52001.servers.mongodirector.com:27017/todo?ssl=true&connectTimeoutMS=10000&authSource=admin

Expected Behavior

gcloud app deploy without errors which deplous when I eliminate databsae connection.

Connection failes using Scalegrid.io

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.27.3

Plugin version

4.1.1

Node.js version

14.18.3

Operating system

Windows

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

10

Description

I'm trybg to update a repo that connects to a number to mongodb databases using sca;egrid.io.
My app that uses the following version works fine

WORKS
  fastify": "^2.6.0",
 "fastify-autoload": "^1.0.0",
 "fastify-cli": "^1.1.0",
 "fastify-mongodb": "^1.0.1",
 "fastify-plugin": "^1.6.0",
 "fastify-session": "^3.3.0",
 "mongodb": "^4.4.1"

const MONGODB_URL_local_todo='mongodb://127.0.0.1:27017/todo'
const MONGODB_URLtodo='mongodb://admin:<Password>@SG-test-fastify-50496.servers.mongodirector.com:27017/todo?ssl=true&connectTimeoutMS=10000&authSource=admin&authSource=admin' // &authMechanism=SCRAM-SHA-1'

async function dbConnector (fastify, options) {
fastify.register(fastifyMongo, {
 // url:MONGODB_URL_local_todo
 url:MONGODB_URLtodo
})
}
the following works with connection string to scalegrid
async function dbConnector (fastify, options) {
  fastify.register(fastifyMongo, {
    url:MONGODB_URLtodo
  })
}

When I update libraries to the following connection fails to scalegrid but works fine to local connection

    "fastify": "^3.27.3",
    "fastify-mongodb": "^4.1.1",
    "fastify-plugin": "^3.0.1",
    "mongodb": "^4.4.1"
    "fastify-autoload": "^3.7.1",
    "fastify-cli": "^2.13.0",
    "fastify-mongodb": "^4.1.1",
    "fastify-plugin": "^3.0.0",

    PS D:\fastify-gp\test-fastify_mongodbA> node app
{"level":50,"time":1648939646981,"pid":17512,"hostname":"DESKTOP-TF4IHHA","reason":{"type":"Unknown","servers":{},"stale":false,"compatible":true,"heartbeatFrequencyMS":10000,"localThresholdMS":15},"stack":"MongoServerSelectionError: self signed 
certificate\n    at Timeout._onTimeout (D:\\fastify-gp\\test-fastify_mongodbA\\node_modules\\mongodb\\lib\\sdam\\topology.js:312:38)\n    at listOnTimeout (internal/timers.js:557:17)\n    at processTimers (internal/timers.js:500:7)","type":"Error","msg":"self signed certificate"}

### Steps to Reproduce

see repo https://github.com/johntom/test-fastify_mongodb

 ////////// populate todo collection in todo database in scalegid.io
     { 
     "_id" : ObjectId("5c1f1314e60a5b0bd0be8066"), 
     "id" : 1.0, 
     "title" : "milk", 
     "desc" : "lower case collection"
     }
   { 
     "_id" : ObjectId("5c204576e60a5b25184c282e"), 
     "id" : 5.0, 
     "title" : "buy milk", 
     "desc" : "need for cereal"
 }
    

### Expected Behavior

I like to see all my connection strings work with scalegrid.io

upgrade to mongo@3

mongo@3 has been a breaking release.

Can someone figure it out and update this?

An in-range update of @types/mongodb is breaking the build 🚨

The devDependency @types/mongodb was updated from 3.1.31 to 3.1.32.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/mongodb is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Mongodb connection error

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.22.1

Plugin version

4.1.1

Node.js version

16.13.0

Operating system

Linux

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

20.04

Description

Hello.
I launched a clustered mongodb and enabled authentication.
But the fastify-mongodb plugin does not connect with authentication (AuthenticationFailed).
But there is no problem with MongoClient.

Steps to Reproduce

const fastify = require("fastify");
const app = fastify();

app.register(require('fastify-multipart'))
app.register(require('fastify-formbody'))
app.register(require('./FastifyRouter'))

//database
app.register(require('fastify-mongodb'), {
    forceClose: true,
    url: 'mongodb://localhost:27017/db',
    auth: {
        username: "username",
        password: "password"
    }
})

app.listen(port,"hostname",(err,adrs) => {
    if (err) {
        console.log(err)
    } else {
        console.log(address)
    }
})

Expected Behavior

No response

Mongodb find({}) error

Prerequisites

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

Issue

I am using this code

const fastify = require('fastify')()

fastify.register(require('@fastify/mongodb'), {
  // force to close the mongodb connection when app stopped
  // the default value is false
  forceClose: true,
  
  url: 'myDb_URL'
})

fastify.get('/user/:id', function (req, reply) {

  const users = this.mongo.db.collection('users')

  users.findOne({ name: "some name" }, (err, user) => {
    if (err) {
      reply.send(err)
      return
    }
    reply.send(user)
  })
})

fastify.listen({ port: 3000 }, err => {
  if (err) throw err
})

By using users.findOne({ name: "some name" }) I am getting data successfully but when I use users.find({}) to get all the users in users collection it is returning {"statusCode":500,"error":"Internal Server Error","message":"Argument \"options\" must not be function"}

This is my final code and I want to get all the users in users document.

const fastify = require("fastify")();

fastify.register(require("@fastify/mongodb"), {
  // force to close the mongodb connection when app stopped
  // the default value is false
  forceClose: true,

  url: "mongodb://localhost:27017",
});

fastify.get("/", function (req, reply) {
  // Or this.mongo.client.db('mydb').collection('users')
  const users = this.mongo.client.db("Store").collection("offers");

  users.find({}, (err, user) => {
    console.log(err);
    if (err) {
      reply.send(err);
      return;
    }
    console.log(user);
    reply.send(user);
  });
});

fastify.listen({ port: 3000 }, (err) => {
  if (err) throw err;
  console.log("Server running on port 3000");
});

Database Selection At Runtime

Prerequisites

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

Issue

I have a mongodb cluster that has about 40 database that I need to selected based on some criteria.
Is there a way that I can use to select the database at runtime instead of passing in URI string ?
I have searched over internet and also in the issues & discord but couldn't find any answer.
Any help would be appreciated.

feat: re-export ObjectId

🚀 Feature Proposal

It is better to re-export ObjectId from mongodb.

Motivation

Better developer experience.

Example

It can simplify the use of mongodb API.
For example, when we want to create helper function with fastify access.

const { ObjectId } = require('fastify-mongodb')

export function findUserById(collection, id) {
  return collection.findOne({ _id: ObjectId(id) })
}

An in-range update of mongodb is breaking the build 🚨

The dependency mongodb was updated from 3.2.7 to 3.3.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

mongodb is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Commits

The new version differs by 1878 commits ahead by 1878, behind by 7.

  • 8b3c3b0 chore(release): 3.3.0
  • 0d2018c docs(AutoEncryption): adds documentation for extraOptions
  • 3ecda98 docs(autoEncryption): document that autoEncryption is in beta
  • 814a4cc chore(useUnifiedTopology): add deprecation warning for useUnifiedTopology
  • b7308db test: disable some failing tests for later investigation
  • b23e606 test(transactions): disable invalid pinning test
  • 82a7a6e chore(travis): add 4.2 testing to travis
  • 392f5a6 fix(topology): add new error for retryWrites on MMAPv1
  • 2ef8f2c chore(ci): update evergreen config to test Ubuntu 18.04 on mongodb >= 4.2
  • ae729f8 refactor(change-stream): use AggregateOperation for stream cursor
  • 831968d refactor(cursor): return operation readPreference with priority
  • 1ffe9b7 refactor(client): provide default namespace and read preference
  • 778928f refactor(command): support full response as command op option
  • 6acef6d refactor(find): use FindOperation for finds
  • 0f88582 refactor(cursor): modernize and deduplicate cursor classes

There are 250 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

How to get reference of fastify instance from a standalone route handler?

How should I get the reference to fastify in this standalone route handler?

handler.js:

module.exports = (req, reply) => {
  const { db } = fastify.mongo // how should I get this `fastify`?
  db.collection('users', onCollection)

  function onCollection (err, col) {
    if (err) return reply.send(err)

    col.findOne({ id: req.params.id }, (err, user) => {
      reply.send(user)
    })
  })
}

index.js:

const fastify = require('fastify')
const handler = require('./handler.js')

fastify.register(require('fastify-mongodb'), { url: 'mongodb://mongo/db' })

fastify.get('/user/:id', handler)

fastify.listen(3000, err => {
  if (err) throw err
  console.log(`server listening on ${fastify.server.address().port}`)
})

Cannot parse databaseName from replicatedDatabase url string

When mongodb is replicated, the library fails to properly find and parse databaseName.
There is easier way to parse the databaseName from url string, that properly finds it

Showing a typical production url string with the solution how to parse it properly

const url = mongodb://user1:Passw0rd1@hostname1:27017,hostname2:27017,hostname3:27017/DBNAME?replicaSet=myReplicaSet1&poolSize=25&readPreference=primaryPreferred&appname=myApp
const dbName = /\d{5}\/([^?]*)/g.exec(url)[1]

This regex solution would also remove the url dependency from this library.
I would recommend to change the code to this logic. I can do a pull request if you are interested.

An in-range update of fastify-plugin is breaking the build 🚨

Version 1.2.0 of fastify-plugin was just published.

Branch Build failing 🚨
Dependency fastify-plugin
Current Version 1.1.3
Type dependency

This version is covered by your current version range and after updating it in your project the build failed.

fastify-plugin is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • continuous-integration/travis-ci/push The Travis CI build failed Details

Release Notes v1.2.0
  • use fp meta name option instead of new symbol #44
Commits

The new version differs by 3 commits.

  • 9e164ab Bumped v1.2.0.
  • cdac717 chore(package): update ts-node to version 7.0.0 (#43)
  • 60832a3 have fp use meta name option instead of new symbol (#44)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

use `useNewUrlParser:true` by default

We should use the new url parser by default in order to remove this message and to be up-to-date.

(node:10772) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect

An in-range update of @types/node is breaking the build 🚨

The devDependency @types/node was updated from 10.12.8 to 10.12.9.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

fastify.ready() always timeout

When calling the ready method from fastify server, mongodb will establish the connection with the mongodb server but it will never return.

'use strict'

const app = require('fastify')()

app.register(require('fastify-mongodb'), {
  url: 'mongodb://localhost/user'
})

app.ready(err => {
  if (err) throw err
  console.log('READY')
})

This snippet will log READY but it will not exit (if you remove fastify-mongodb registering, it logs READY and return)

I noticed this bug when I was writing tap tests, I tried to await fastify.ready() in order to test my service decorator, but it always timeout. Adding forceClose does not change the behavior of fastify-mongodb.

fastify-mongodb: 1.0.0
fastify: 1.13.3

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! 🎊

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Added the new Node.js version to your .travis.yml

If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didn’t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected 🤖


FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

bump mongo version

node version 14.5.x

Warning at runtime:
(node:10928) Warning: Accessing non-existent property 'MongoError' of module exports inside circular dependency
(Use node --trace-warnings ... to show where the warning was created)

Did not appear in node 12.x:

Fix:
Fix has been made in MongoDB Node.JS Driver
https://jira.mongodb.org/browse/NODE-2536

additional reference
https://developer.mongodb.com/community/forums/t/warning-accessing-non-existent-property-count-of-module-exports-inside-circular-dependency/3183

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.