如何从另一个js文件/函数中获取mongoose post hook?

问题描述 投票:0回答:1

我有这个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');
  });
}

如果我将钩子放在模型itseld中,那么mongoose post save钩子工作正常。但是当我放在location.socket.js文件中时,同一个钩子不会被触发。所以我需要的是从这个location.socket.js文件中执行socket.emit

Edit1:这是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);
  })
}
javascript node.js express mongoose mean-stack
1个回答
0
投票

请试试这个: -

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

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

但这将发送到每个连接的套接字。因此,如果你需要发射到特定的插座,你需要在socketio中使用房间。

© www.soinside.com 2019 - 2024. All rights reserved.