Skip to content

Instantly share code, notes, and snippets.

@luciyer
Created October 11, 2020 01:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luciyer/5d47972011e72cb6d864187b4e8bd2ab to your computer and use it in GitHub Desktop.
Save luciyer/5d47972011e72cb6d864187b4e8bd2ab to your computer and use it in GitHub Desktop.
Mongoose Hooks to Emit Events
const events = require("events")
module.exports = new events.EventEmitter();
const mongoose = require("mongoose")
const emitter = require("./emitter")
const wineSchema = new mongoose.Schema({
name: String,
price: Number
})
wineSchema.post("save", (wine) => {
emitter.emit("wineCreated", wine)
})
module.exports = mongoose.model("Wine", wineSchema)
const express = require("express"),
mongoose = require("mongoose");
const Wine = require("./model"),
emitter = require("./emitter");
const app = express()
const dbUri = process.env.MONGODB_URI || "mongodb://localhost/dev";
const dbOptions = {
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
}
mongoose.connect(dbUri, dbOptions)
.then(console.log("Connected to DB."))
.catch(console.error)
emitter.on("wineCreated", (wine) => {
console.log("Created:", wine)
})
app.listen(8080)
app.get("/", async (req, res) => {
await new Wine({ name: "My Wine", price: 20 }).save()
res.sendStatus(200)
})
@luciyer
Copy link
Author

luciyer commented Oct 11, 2020

Making a GET request to localhost:8080/ will cause a Wine record to be inserted, which will cause the "wineCreated" event to be fired. This can be used to have database operations drive events, allowing for a cleaner separation of concerns (versus a middleware which interfaces with the DB and acts as a logic layer).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment