首页 > 解决方案 > 如何使用 MongoDB 数据源在 LoopBack 4 中增加计数器变量?

问题描述

我正在尝试将我的 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;
            }
        }
    );
};

我尝试先获取 counter 的值然后递增,但每次保存 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);
  }

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

添加到帮助解决方案 我的 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);
  }

标签: mongodbloopback4

解决方案


您可以使用 mongo update-operators

基本上,您只需设置allowExtendedOperators=trueMongoDB 数据源定义(指南)。之后,您可以直接使用这些运算符。

使用示例:

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

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

您可以关注此问题以查看这些运算符的情况。


推荐阅读