-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.js
More file actions
38 lines (33 loc) · 1.22 KB
/
db.js
File metadata and controls
38 lines (33 loc) · 1.22 KB
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
import mongoose from "mongoose";
import path from "path";
import { Items } from "./model.js";
const mongoDbCollection = process.env.MONGODB_COLLECTION || 'itemsdb';
const mongoDbHost = process.env.MONGODB_HOST || 'localhost';
const mongoDbUsername = process.env.MONGODB_USERNAME || '';
const mongoDbPassword = process.env.MONGODB_PASSWORD || '';
async function connectWithOptions() {
if (mongoDbUsername && mongoDbPassword) {
let caFile = path.join('global-bundle.pem');
let options = {
tls: true,
tlsCAFile: caFile,
replicaSet: 'rs0',
readPreference: 'secondaryPreferred',
retryWrites: false
}
await mongoose.connect(`mongodb://${mongoDbUsername}:${mongoDbPassword}@${mongoDbHost}/${mongoDbCollection}`, options);
} else {
await mongoose.connect(`mongodb://${mongoDbHost}/${mongoDbCollection}`);
}
}
async function connectMongo() {
try {
// mongoose will create the database if it doesn't exist
await connectWithOptions();
console.log(`Connected to MongoDB @ ${mongoDbHost}`);
} catch (error) {
console.log('Error connecting to MongoDB:', error);
}
}
connectMongo();
export { Items };