LOOPBACK修改钩子内的另一个模型

时间:2017-11-17 04:25:10

标签: node.js loopbackjs

当事务模型中的属性“code”等于3

时,我想在事件模型中插入新数据
 module.exports = function(Transaction) {
    Transaction.observe('before save', function(ctx, next) {
        if(ctx.data.code == 3){
          //How to access and insert data in Event model ?
        }
    });
};

3 个答案:

答案 0 :(得分:1)

这对我有用。就像@Sunil喇嘛所说的那样,但我还使用了loopback.getModel

server.js

const loopback = require('loopback');
const ModelInst = require('./model-instnace');
boot(app, __dirname, function (err) {
   if (err) throw err;
   ModelInst.event = (loopback.getModel('event'));
};  

模型instance.js

const ModelInst = {
    ...
    event:null
    ...
}

model.js

const models = require('model-instnace Path');
module.exports = function(Transaction) {
    Transaction.observe('before save', function(ctx, next) {
        if(ctx.data.code == 3){
            models.event.insertNewDate('blah');
        }
    });
};

答案 1 :(得分:0)

如果您的事件模型具有插入newData的函数。只需参考模型。例如:

var eventModel = require('pathtoEventModel');  

module.exports = function(Transaction) {
Transaction.observe('before save', function(ctx, next) {
    if(ctx.data.code == 3){
       eventModel.saveNewData(ctxBeingNewData,function(response,next){
       //manipulate as per your wish.
       })
    }

}); };

答案 2 :(得分:-1)

这对我有用

module.exports = function(Transaction) {
  Transaction.observe('before save', function(ctx, next) {
    if(ctx.data.code == 3){
      var eventModel = Transaction.app.models.Event;
      eventModel.create({"nom":"ZONA ABC"}, function(err, obj){
        //console.log('eventModel create', err);
      });
    }
  });
};