Created
October 11, 2020 01:23
-
-
Save luciyer/5d47972011e72cb6d864187b4e8bd2ab to your computer and use it in GitHub Desktop.
Mongoose Hooks to Emit Events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const events = require("events") | |
module.exports = new events.EventEmitter(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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).