serverless, mongoose multiple databases
Answered
Bananaquit posted this in #help-forum
BananaquitOP
hey. im trying to setup mongoose in my nextjs project to be deployed on vercel. all the examples im seeing of mongoose using some async connection function are only when the connection has 1 database, eg.
in atlas, i have multiple database names, with multiple collections. im trying to figure out the best way to import connections and models given that.
i'm currently led to believe to export these functions per model, and when imported to await/assign as the model to use:
but it seems excessive? compared to mongodb, prisma, or drizzle examples of just passing around the client
dbName="database"
or .useDb("database")
. in atlas, i have multiple database names, with multiple collections. im trying to figure out the best way to import connections and models given that.
i'm currently led to believe to export these functions per model, and when imported to await/assign as the model to use:
// db/models/company/tickers.ts
import mongoose from "mongoose";
import { connectMongo } from "../../lib/connection";
import { DB_NAMES } from "../../lib/constants";
export interface ITicker {
symbol: string;
name: string;
sector: string;
}
const tickerSchema = new mongoose.Schema({
symbol: { type: String, required: true, unique: true },
name: { type: String, required: true },
sector: String,
});
export async function getTickerModel() {
await connectMongo();
const db = mongoose.connection.useDb(DB_NAMES.COMPANY);
return db.models.tickers || db.model("tickers", tickerSchema);
}
but it seems excessive? compared to mongodb, prisma, or drizzle examples of just passing around the client
Answered by Anay-208 | Ping in replies
I believe this is a requirement for using MongoDB in serverless applications.
You can use prisma otherwise, it supports mongoDB
You can use prisma otherwise, it supports mongoDB