Should we declare mongoose schema in database connection script?
Hello, I have a simple question, when we use
mongoose, noticed that I've defined my schema when I need to fetch a particular document from the database. Is that good practice or we need to define the schema in the script where we launch db connection?
Now speaking of db connection, should we keep it opened? Like as soon as express server is launched, open database connection? Or we open and close for each request we need?6 Replies
Your schema should be declared once before anything else happens. Right now you're creating and using a new schema (technically) each time you update the user's profile picture. That's a lot of wated cycles.
As for keeping it open…that depends, I think. I'm not a MongoDB user so I'm just guessing, but if you're app does a lot of DB reads/writes then keeping it open cuts down on the connection time, but increases usege as it keeping a connection open takes resources. If the DB is not frequently read from/written to then open and close per use would be more resource-efficient I think.
I use SQLite so every read/write is a simple read/write to the local file system, no socket overhead needed. 🤷
Yep I see, I take notes, will also just shift the schema in another file so that when db is connected, everything is loaded
the open db connection depends on whether I'm expecting multiple requests to the db or not ? Like if we expect multiple request, it's better to leave it open ?
From what I remember from years ago while learning MongoDB, you should create your schemas in a seperate file and import them where they're used
yep noted
It depends on the frequency of reads/writes. By design there will always be multiple requests to your DB. But the frequency of said requests should determine if you want to keep the connection alive.
Of course, you should read the MongoDB and Mongoose docs to see what they recommend, as that's going to be the Single Source of Truth™️
yep got it, thanks !!