如何在 sailsjs 生命周期方法中循环集合?

how can I loop over a collection in a sailsjs lifecycle method?

我是 sailsjs 的新手,所以这可能是一件简单的事情,但我似乎找不到我想要的东西。在我的 MyModel 中,我想遍历事物集合并获取 things.id 字段的列表(我正在使用 mySQL)并将它们填充到 values.schedule 字符串中并使用 MyModel 保存记录。 我怎样才能在 MyModel 的 afterUpdate 或 afterCreate 方法中做到这一点?它需要在那里完成,因为 things 集合是在创建 MyModel 时填充的。假设 MyThing 模型非常简单,只有一个名称和它自己的 id 字段以及 MyModel.id 字段或引用。

 /**
 * MyModel.js
 */

module.exports = {

  schema: true,
  tableName: 'my_model',
  autoCreatedAt: false,
  autoUpdatedAt: false,

  attributes: {

    id: {
      type: 'integer',
      unique: true,
      primaryKey: true,
      autoIncrement: true
    },
    things: {
      collection: "MyThing",
      via: 'MyModel'
    },

    schedule: {
      columnName: 'schedule',
      type: 'json',
      size: 512
    },
    ... other attributes ...

    toJSON: function() {
      var obj = this.toObject();
      return obj;
    }

  },

  .... other methods ...

  afterUpdate: function(values,  cb) {
    console.log('afterUpdate  : ', values);
    var things =  MyThing.find({
      where: {myModel: values.id},
      select: ['id']
    });
    console.log('MyModel afterUpdate  : ', things);
    cb();
  }
};

在上面的代码中我会得到错误:

ReferenceError: MyThing is not defined

感谢您的帮助。

更新:

这是让我得到东西的代码:

afterCreate: async function(values, next) {
...
  var things =  await MyThing.find({
      where:  {myModel: values.id},
      select: ['id']
    });
...
}

afterUpdatetheUpdatedRecord 作为第一个参数,因此您可以这样做:

  afterUpdate: async function(updatedRecord,  cb) {
               console.log('afterUpdate  : ', updatedRecord);
               var things =  await MyModel.find({ id: 
               updatedRecord.id}).populate('things');
               var ids = things.map(thing => thing.id));
               console.log('MyModel afterUpdate  : ', ids); 
               cb();
              }

afterUpdate will only be run on queries that have the fetch meta flag set to true.