diff options
author | terminaldweller <thabogre@gmail.com> | 2022-07-06 13:34:45 +0000 |
---|---|---|
committer | terminaldweller <thabogre@gmail.com> | 2022-07-06 13:34:45 +0000 |
commit | da98e1dee68e421bdd7cfcf332c43a1f94a43a30 (patch) | |
tree | 792f70ee92e096d69d9989481a736ff3af0590c7 /model.js | |
parent | was using node image for self-signed certificates (diff) | |
parent | fix for atom (diff) | |
download | blog-da98e1dee68e421bdd7cfcf332c43a1f94a43a30.tar.gz blog-da98e1dee68e421bdd7cfcf332c43a1f94a43a30.zip |
Merge branch 'rss'
Diffstat (limited to '')
-rw-r--r-- | model.js | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/model.js b/model.js new file mode 100644 index 0000000..dde3913 --- /dev/null +++ b/model.js @@ -0,0 +1,62 @@ +"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: fileName, + body: fileContent, + teaser: fileName, + keywords: ["kw1", "kw2"], + }); + newBlogPost.save(); + }); +} + +module.exports = { + blogPost: mongoose.model("BlogPost", BlogPostSchema), + dbInit: dbInit, + populateDB: populateDB, +}; |