在调用对象的构造方法时触发/捕获事件

时间:2019-01-28 15:57:25

标签: node.js mongodb events mongoose

我是Node.js和Mongoose的新手,我想在对象构造函数启动时触发/捕获事件。

即,我想在创建这样的角色时发送电子邮件:

controller.on('characterCreated', (mail, objectCreated) => {
    mailSenderFunction(mail, objectCreated);
});

我在使用MongoDB和mongoose的node.js结构Model / Service / Controller上:

characterModel.js

const mongoose = require('mongoose');
const characterSchema = new mongoose.Schema({
    name: String,
    age: Number,
});

var Character = mongoose.model('Character', characterSchema);

module.exports = Character;

characterService.js

const Character = require('../models/modelCharacter.js');

function create(name, age) {
  return (new Promise((resolve, reject) => {
      const character = new Character();
      character.name = name;
      character.age = age;

      character.save((err) => {
        if (err) {
          reject({ status: 500, error: err });
        } else {
          resolve({ status: 202, data: character });
        }
      });
  }));
}

module.exports = {
    create,
};

characterController.js

const charService = require('../services/characterService');

function create(req, res) {
  if (req.body.name && req.body.age) {
      charService.create(req.body.name, req.body.age);
          .then((result) => {
              res.json(result.data);
              res.status(result.status).end();
          })
          .catch((error) => {
              res.status(result.status).end();
          })
  } else {
      res.status(404).end();
  }
}

module.exports = {
    create,
};

api.js:

const router = require('express').Router();
const characterController = require('./routes/characterController');

router
    .route('/characters')
    .post(characterController.create);

我的第一个想法是这样做:

const EventEmitter = require('events');

const myEmitter = new EventEmitter();
myEmitter.on('myCustomEvent', (mail, data) => {
    mailSenderFunction(mail, objectCreated);
})

并像这样使用它:

characterService.js:

...
const character = new Character();
...
character.save((err) => {
...
    myEmitter.emit('myCustomEvent', mail, character);
})
...

但是我看到猫鼬可能使我们听到了有关数据库事件的信息,但我没有找到具体方法。

有猫鼬方法或其他方法吗?谢谢。

1 个答案:

答案 0 :(得分:0)

u可以使用pre来发送邮件,例如

with open("helloworld.txt", "r") as filec: # changed here
    fcontent = filec.readlines()           # added this line
    lc = 0
    for eachline in fcontent:
        lc += 1
        if fcontent.count(eachline) > 1:
            print(lc,eachline)

此代码在.save之前执行

如果您需要在保存后发送,请参见https://mongoosejs.com/docs/api.html#schema_Schema-post