CNode

eggjs的service中该如何调用model中实现的实例方法?

问答
Ffengyun2发布于8 年前最后回复8 年前3 回复4138 浏览0 收藏

例如:

// ./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)

O
okoala#1·8 年前

ctx.model.ids.getId ?

F
fengyun2#2·8 年前
引用 okoalactx.model.ids.getId ?

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

A
aojiaotage#3·8 年前

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

参与回复
登录后即可参与回复。登录