如何使用 MongoDB 数据源增加 LoopBack 4 中的计数器变量?

How can I increment a counter variable in LoopBack 4 with a MongoDB datasource?

我正在尝试将我的 Nodejs Express 应用程序转换为 Loopback 4,但我不知道如何增加计数器。在我的 Angular 9 应用程序中,当用户单击图标时,计数器会增加。这在 Express

中完美运行

快递

const updateIconCount = async function (dataset, collection = 'icons') {
    let query = { _id: new ObjectId(dataset.id), userId: dataset.userId };
    return await mongoController.update(
        collection,
        query,
        { $inc: { counter: 1 } },
        function (err, res) {
            logAccess(res, 'debug', true, 'function update updateIconLink');
            if (err) {
                return false;
            } else {
                return true;
            }
        }
    );
};

我尝试先获取计数器的值然后递增,但每次我保存 VS Code 时都会以一种不寻常的方式重新格式化代码。在此片段中,我注释掉了导致重新格式化的代码行。我可以设置计数器值,例如100.

环回 4

@patch('/icons/count/{id}', {
    responses: {
      '204': {
        description: 'Icons PATCH success',
      },
    },
  })
  async incrementCountById(
    @param.path.string('id') id: string,
    @requestBody({
      content: {
        'application/json': {
          schema: getModelSchemaRef(Icons, {partial: true}),
        },
      },
    })
    icons: Icons,
  ): Promise<void> {
    // let targetIcon = this.findById(id).then(icon => {return icon});
    icons.counter = 100;
    console.log(icons.counter);
    await this.iconsRepository.updateById(id, icons);
  }

如何在 Loopback 4 中实现 { $inc: { counter: 1 } }

添加到辅助解决方案 我的mongo.datasource.ts

import {inject, lifeCycleObserver, LifeCycleObserver} from '@loopback/core';
import {juggler} from '@loopback/repository';

const config = {
  name: 'mongo',
  connector: 'mongodb',
  url: '',
  host: '192.168.253.53',
  port: 32813,
  user: '',
  password: '',
  database: 'firstgame',
  useNewUrlParser: true,
  allowExtendedOperators: true,
};

// Observe application's life cycle to disconnect the datasource when
// application is stopped. This allows the application to be shut down
// gracefully. The `stop()` method is inherited from `juggler.DataSource`.
// Learn more at https://loopback.io/doc/en/lb4/Life-cycle.html
@lifeCycleObserver('datasource')
export class MongoDataSource extends juggler.DataSource
  implements LifeCycleObserver {
  static dataSourceName = 'mongo';
  static readonly defaultConfig = config;

  constructor(
    @inject('datasources.config.mongo', {optional: true})
    dsConfig: object = config,
  ) {
    super(dsConfig);
  }
}

修正端点

@patch('/icons/count/{id}', {
    responses: {
      '204': {
        description: 'Icons PATCH success',
      },
    },
  })
  async incrementCountById(
    @param.path.string('id') id: string,
    @requestBody({
      content: {
        'application/json': {
          schema: getModelSchemaRef(Icons, {partial: true}),
        },
      },
    })
    icons: Icons,
  ): Promise<void> {
    console.log(id);
    // @ts-ignore
    await this.iconsRepository.updateById(id, {$inc: {counter: 1}});//this line fails
    // icons.counter = 101; //these lines will set the icon counter to 101 so I know it is connecting to the mongodb
    // await this.iconsRepository.updateById(id, icons);
  }

您可以使用 mongo update-operators.

基本上,您只需在 MongoDB 数据源定义 (guide) 中设置 allowExtendedOperators=true。之后就可以直接使用这些运算符了。

用法示例:

// increment icon.counter by 3
await this.iconsRepository.updateById(id, {$inc: {counter: 3}} as Partial<Counter>);

目前,lb4 类型中缺少这些运算符,因此您必须欺骗 typescript 才能接受它们。这很难看,但这是我现在能找到的唯一解决方案。

你可以关注this issue看看这些操作符是怎么回事。