eggjs的service中该如何调用model中实现的实例方法?
发布于 5 年前 作者 fengyun2 2652 次浏览 来自 问答

例如:

// ./model/ids.js
  const Ids = mongoose.model('Ids', idsSchema);

  idsSchema.methods.getId = async function(type) {
    const idList = [
      'restaurant_id',
      'food_id',
      'order_id',
      'user_id',
      'address_id',
      'cart_id',
      'img_id',
      'category_id',
      'item_id',
      'sku_id',
      'admin_id',
      'statis_id',
    ];

    if (!idList.includes(type)) {
      console.log('id类型错误');
      throw new Error('id 类型错误');
    }
    try {
      const idData = await Ids.findOne();
      idData[type]++;
      await idData.save();
      return idData[type];
    } catch (err) {
      console.log('获取ID数据失败');
      throw new Error(err);
    }
  };

serive 中该如何读取 getId 这个实例方法呢?

3 回复

ctx.model.ids.getId ?

@okoala ctx.model.Ids.getId is not a function

注意实例方法和类方法哈,你这个挂在methods上的话,实际上要拿到一个具体的model,new出来或者查出来之后直接在对象上使用的, ctx.model.Ids.getId 应该是类方法 可以再看看mongoose文档

回到顶部