Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Cache mongo client, not client promise #1

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

Merged
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
17 changes: 7 additions & 10 deletions lib/mongodb.ts
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,24 @@ if (!process.env.MONGODB_URI) {
const uri = process.env.MONGODB_URI;
const options = {};

let client;
let clientPromise: Promise<MongoClient>;
let client: MongoClient;

if (process.env.NODE_ENV === "development") {
// In development mode, use a global variable so that the value
// is preserved across module reloads caused by HMR (Hot Module Replacement).
let globalWithMongo = global as typeof globalThis & {
_mongoClientPromise?: Promise<MongoClient>;
_mongoClient?: MongoClient;
Copy link

@nbbeeken nbbeeken Jun 6, 2024
edited
Loading

Choose a reason for hiding this comment

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

types/mongodb.d.ts still references the old global.

Optional, can we use globalThis (instead of global) here? Sticks out as legacy to me, but not necessary.

};

if (!globalWithMongo._mongoClientPromise) {
client = new MongoClient(uri, options);
globalWithMongo._mongoClientPromise = client.connect();
if (!globalWithMongo._mongoClient) {
globalWithMongo._mongoClient = new MongoClient(uri, options);
}
clientPromise = globalWithMongo._mongoClientPromise;
client = globalWithMongo._mongoClient;
} else {
// In production mode, it's best to not use a global variable.
client = new MongoClient(uri, options);
clientPromise = client.connect();
}

// Export a module-scoped MongoClient promise. By doing this in a
// Export a module-scoped MongoClient. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise;
export default client;
3 changes: 1 addition & 2 deletions pages/api/movies.tsx
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import clientPromise from "../../lib/mongodb";
import client from "../../lib/mongodb";
import { NextApiRequest, NextApiResponse } from 'next';

export default async (req: NextApiRequest, res: NextApiResponse) => {
try {
const client = await clientPromise;
const db = client.db("sample_mflix");
const movies = await db
.collection("movies")
Expand Down
6 changes: 3 additions & 3 deletions pages/index.tsx
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Head from "next/head";
import clientPromise from "../lib/mongodb";
import client from "../lib/mongodb";
import type { InferGetServerSidePropsType, GetServerSideProps } from "next";

type ConnectionStatus = {
Expand All @@ -10,8 +10,8 @@ export const getServerSideProps: GetServerSideProps<
ConnectionStatus
> = async () => {
try {
await clientPromise;
// `await clientPromise` will use the default database passed in the MONGODB_URI
await client.connect();
// `await client.connect()` will use the default database passed in the MONGODB_URI
Comment on lines +13 to +14
Copy link

@nbbeeken nbbeeken Jun 6, 2024

Choose a reason for hiding this comment

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

I am not sure what it means for connect to "use a database" and the line below still references "clientPromise".

I would uncomment the sample find code, just cutting to the chase so to speak.

// However you can use another database (e.g. myDatabase) by replacing the `await clientPromise` with the following code:
//
// `const client = await clientPromise`
Expand Down
3 changes: 1 addition & 2 deletions pages/movies.tsx
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import clientPromise from "../lib/mongodb";
import client from "../lib/mongodb";
import { GetServerSideProps } from 'next';

interface Movie {
Expand Down Expand Up @@ -36,7 +36,6 @@ export default Movies;

export const getServerSideProps: GetServerSideProps = async () => {
try {
const client = await clientPromise;
const db = client.db("sample_mflix");
const movies = await db
.collection("movies")
Expand Down
4 changes: 1 addition & 3 deletions pages/top.tsx
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ObjectId } from "mongodb";
import clientPromise from "../lib/mongodb";
import client from "../lib/mongodb";
import { GetStaticProps } from "next";

interface Movie {
Expand Down Expand Up @@ -35,8 +35,6 @@ export default function Top({ movies }: TopProps) {

export const getStaticProps: GetStaticProps<TopProps> = async () => {
try {
const client = await clientPromise;

const db = client.db("sample_mflix");

const movies = await db
Expand Down

AltStyle によって変換されたページ (->オリジナル) /