如何获取从另一个js文件/函数触发的猫鼬后钩?

时间:2019-03-14 08:17:49

标签: javascript node.js express mongoose mean-stack

我有这个location.model.js,

'use strict';

var mongoose = require('mongoose'),
Schema = mongoose.Schema;

var LocationsSchema = new Schema({
 name: String,
 description: String,
 country_id:{
    type: Schema.Types.ObjectId,
    ref: 'Countries'
 },
 geo_location:{
    type: [Number] 
 },
 icon: String,
 image: String,
 status: {
    type: Boolean,
    default: true
 },
 created_at : {
    type: Date,
    default: new Date()
 },
 updated_at: {
    type: Date
 }
});
LocationsSchema.index({ geo_location: "2dsphere" });
module.exports = mongoose.model('Locations', LocationsSchema);

我进行查询,例如从控制器文件中查找,保存,更新。 我有这样的location.socket文件。

'use strict';
var locations = require('./locations.model');

exports.register = function(socket) {
  //socket.emit('locations:save', 'Helloooo');
  locations.schema.post('save', function (doc) {
    console.log('new location added');
  });
}

如果我将该猫鼬放置在模型字段中,则该猫鼬后保存钩工作正常。但是当我将其放置在location.socket.js文件中时,不会触发相同的钩子。 所以我所要做的就是从这个location.socket.js文件中进行socket.emit

编辑1: 这是app.js(服务器启动文件)

    var server = require('http').createServer(app);
    var socketio = require('socket.io')(server, {
      serveClient: config.env !== 'production',
      path: '/socket.io'
    });
    require('./config/socketio')(socketio);
    require('./config/express')(app);
    require('./routes')(app);

    server.listen(config.port, config.ip, function () {
          console.log('server started');
    });

这是socketio配置文件,

module.exports = function (socketio) {
  socketio.on('connection', function (socket) {
    require('../api/locations/locations.socket').register(socket);
  })
}

1 个答案:

答案 0 :(得分:0)

请尝试以下操作:-

module.exports = function (socketio) {
  require('../api/locations/locations.socket').register(socketio)
}

exports.register = function(socketio) {
  socketio.emit('locations:save', 'Helloooo');
}

但这会散发出到每个连接的套接字上。因此,如果您需要发射到特定的套接字,则需要使用socketio中的房间。