Should we declare mongoose schema in database connection script?

async function updateProfilePicture(newFileName) {
await connectDB();
try {

const userSchema = new mongoose.Schema({
name: String,
profilePic: String
});
const User = mongoose.model('User', userSchema,'users');
const res = await User.updateOne({name:"John"},{profilePic:`${newFileName}`})
console.log(res);

console.log("Updated");
} catch (error) {
console.error(error.message);
throw error;
}
}
async function updateProfilePicture(newFileName) {
await connectDB();
try {

const userSchema = new mongoose.Schema({
name: String,
profilePic: String
});
const User = mongoose.model('User', userSchema,'users');
const res = await User.updateOne({name:"John"},{profilePic:`${newFileName}`})
console.log(res);

console.log("Updated");
} catch (error) {
console.error(error.message);
throw error;
}
}
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
13eck
13eck7mo ago
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. 🤷
Faker
FakerOP7mo ago
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 ?
13eck
13eck7mo ago
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
Faker
FakerOP7mo ago
yep noted
13eck
13eck7mo ago
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™️
Faker
FakerOP7mo ago
yep got it, thanks !!

Did you find this page helpful?