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
|
"use strict";
const fs = require("fs");
const path = require("path");
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
const db = {};
db.mongoose = mongoose;
const db_pass = fs.readFileSync("/run/secrets/mongo_pass").toString();
const db_user = fs.readFileSync("/run/secrets/mongo_user").toString();
db.url = "mongodb://" + db_user + ":" + db_pass + "@mongo:27017";
const BlogPostSchema = new Schema({
title: { type: String, required: true, trim: true },
slug: { type: String, required: true, lowercase: true, trim: true },
body: { type: String, required: true },
teaser: { type: String, required: true },
keywords: { type: Array, required: true },
lastUpdatedAt: { type: Number },
});
// a simple hook to update the timestamp(lastUpdatedAt) on update
BlogPostSchema.pre("save", function (next) {
this.lastUpdatedAt = Date.now();
next();
});
function dbInit() {
db.mongoose
.connect(db.url, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log("successfully connected to db");
})
.catch((err) => {
console.log("cannot connect to the database: ", err);
process.exit(1);
});
}
function populateDB(model) {
let filePaths = fs.readdirSync(path.join(__dirname, "mds"));
filePaths.forEach((fileName) => {
let fileContent = fs
.readFileSync(path.join(__dirname, "mds", fileName), "utf-8")
.toString();
let newBlogPost = new model({
title: fileName,
slug: "slug",
body: fileContent,
teaser: "teaser",
keywords: ["kw1", "kw2"],
});
newBlogPost.save();
});
}
module.exports = {
blogPost: mongoose.model("BlogPost", BlogPostSchema),
dbInit: dbInit,
populateDB: populateDB,
};
|