Skip to content

Instantly share code, notes, and snippets.

@roelvan
Last active December 20, 2019 01:43
Show Gist options
  • Save roelvan/05947243ca16c453a87d86b8276656e9 to your computer and use it in GitHub Desktop.
Save roelvan/05947243ca16c453a87d86b8276656e9 to your computer and use it in GitHub Desktop.
NOW v2 Error: MongoClient must be connected before calling MongoClient.prototype.db
const { send } = require('micro');
const { handleErrors } = require('../../../lib/errors');
const cors = require('../../../lib/cors')();
const qs = require('micro-query');
const mongo = require('../../../lib/mongo');
const { ObjectId } = require('mongodb');
const handler = async (req, res) => {
let { limit = 5, exclude = '' } = qs(req);
limit = parseInt(limit);
limit = limit > 10 ? 10 : limit;
const db = await mongo();
// fetches random games
const games = await db
.collection('games_v3')
// this avoids showing the main quiz between the random results
.aggregate([
{
$match: {
_id: { $ne: exclude.length > 0 ? ObjectId(exclude) : null },
removed: { $ne: true }
}
},
{ $sample: { size: limit } },
{ $project: { questions: 0, airtableId: 0, removed: 0 } }
])
.toArray();
send(res, 200, games);
};
module.exports = handleErrors(cors(handler));
// Based on: https://spectrum.chat/zeit/now/now-2-0-connect-to-database-on-every-function-invocation~e25b9e64-6271-4e15-822a-ddde047fa43d?m=MTU0NDkxODA3NDExMg==
const MongoClient = require('mongodb').MongoClient;
if (!process.env.MONGODB_URI) {
throw new Error('Missing env MONGODB_URI');
}
let client = null;
module.exports = function getDb(fn) {
if (client && !client.isConnected) {
client = null;
console.log('[mongo] client discard');
}
if (client === null) {
client = new MongoClient(process.env.MONGODB_URI, {
useNewUrlParser: true
});
console.log('[mongo] client init');
} else if (client.isConnected) {
console.log('[mongo] client connected, quick return');
return client.db(process.env.MONGO_DB_NAME);
}
return new Promise((resolve, reject) => {
client.connect(err => {
if (err) {
client = null;
console.error('[mongo] client err', err);
return reject(err);
}
console.log('[mongo] connected');
resolve(client.db(process.env.MONGO_DB_NAME));
});
});
};
{
"version": 2,
"name": "kwis-app-api-v3",
"alias": "api-v2.kwis.app",
"builds": [{ "src": "api/**/index.js", "use": "@now/node" }],
"routes": [
{
"src": "/games/random",
"methods": ["GET", "OPTIONS"],
"dest": "/api/games/random/index.js"
},
{
// other routes
}
],
"env": {
"...": "..."
}
}
@roelvan
Copy link
Author

roelvan commented Dec 20, 2019

@Juanmaster that is what is happening I think (but with a Promise instead of async/await).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment