-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathindex.ts
71 lines (59 loc) · 1.45 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import mongoose from 'mongoose';
// Define mongoose schemas
const userSchema = new mongoose.Schema({
username: { type: String },
password: String,
purchasedCourses: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Course' }]
});
const adminSchema = new mongoose.Schema({
username: String,
password: String
});
export type adminType = {
username: string,
password: string,
_id?: string
}
const courseSchema = new mongoose.Schema({
title: String,
description: String,
price: Number,
imageLink: String,
published: Boolean
});
export type CourseType = {
title: string,
description: string,
price: number,
imageLink: string,
published: boolean,
_id?: string
}
const getModel = (modelName: any, schema: any) => {
try {
return mongoose.model(modelName);
} catch (error) {
// Model does not exist, define and return it
return mongoose.model(modelName, schema);
}
};
const User = getModel('User', userSchema);
const Admin = getModel('Admin', adminSchema);
const Course = getModel('Course', courseSchema);
const { MONGODB_URI } = process.env;
// Ensure that the MongoDB connection is established
async function dbConnect() {
if (!MONGODB_URI || MONGODB_URI.length == 0) {
throw new Error('Please define the MONGODB_URI environment variable');
}
if (mongoose.connection.readyState >= 1) {
return;
}
return mongoose.connect(MONGODB_URI, { dbName: 'cr' });
}
export {
User,
Admin,
Course,
dbConnect,
}