Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Style improvements on MongoDB example #20515

Merged
merged 5 commits into from
Dec 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion examples/with-mongodb/pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ export default function Home({ isConnected }) {
export async function getServerSideProps(context) {
const { client } = await connectToDatabase()

const isConnected = await client.isConnected() // Returns true or false
const isConnected = await client.isConnected()

return {
props: { isConnected },
Expand Down
18 changes: 15 additions & 3 deletions examples/with-mongodb/util/mongodb.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,30 +16,42 @@ if (!MONGODB_DB) {

/**
* Global is used here to maintain a cached connection across hot reloads
* in development. This prevents connections growing exponentiatlly
* in development. This prevents connections growing exponentially
* during API Route usage.
*/
let cached = global.mongo
if (!cached) cached = global.mongo = {}

if (!cached) {
cached = global.mongo = {}
}

export async function connectToDatabase() {
if (cached.conn) return cached.conn
if (cached.conn) {
return cached.conn
}

if (!cached.promise) {
const conn = {}

const opts = {
useNewUrlParser: true,
useUnifiedTopology: true,
}

cached.promise = MongoClient.connect(MONGODB_URI, opts)
.then((client) => {
conn.client = client

return client.db(MONGODB_DB)
})
.then((db) => {
conn.db = db

cached.conn = conn
})
}

await cached.promise

Comment on lines +23 to +55
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@LauraBeatris We only worry about changes requested by eslint and prettier. Code style changes like this aren't required and it's never going to be perfect for everybody (I for example don't like that much spacing), so don't worry too much about this in the future.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got it!

return cached.conn
}