如何使用 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;
            }
        }
    );
};

我试图首先获取计数器的值然后递增,但每次我保存 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 中实现

添加到帮助解决方案 My 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

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

用法示例:

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

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

loopback4 应用中数据源的环境特定配置

如何在Strongloop Loopback框架中为模型配置两个不同的数据源?

为什么我的数据源没有在 LoopBack 4 中从“内存数据库”转换到 MySQL?

使用功能中的数据源(动态数据源)-Select2 v4

如何在 Loopback 4 存储库中调用 MongoDB 的“$inc”?

Terraform中如何使用数据源?

我想在MVC 4中使用模型设置rdlc报告的数据源

如何在SQLAlchemy中增加计数器

如何在CSS代码中增加计数器?

如何基于Pandas数据框的条件增加计数器?

在JBoss 7中配置MongoDB数据源

如何限制Rails4-Autocomplete的数据源

如何将 FetchXML 数据源转换为 SQL 服务器数据源?

如何用SSIS包中的OLE DB数据源替换ODBC数据源?

领域作为Tableview的数据源-如何在数据源中存储不同的对象

Swift 4中的NSTableView数据源非法

如何使用angular4将数据绑定到mat-table数据源?

在Loopback 4中使用服务

使用变量过滤复制数据源

使用flask变量作为高图的数据源

在 Apollo GraphQL 中如何访问 Dataloader 中的数据源?

否则如何在jsp中的星号之间使用advance增加计数器?

如何使用 Getx 在 Flutter 中为特定列表项增加计数器?

如何在Wildfly 10中配置数据源?

如何在测试类中模拟JNDI数据源

如何在MySQL数据源中设置jdbc ClientInfo

如何在Spring中更新数据源bean?

如何在Spring中配置数据源?

如何在JBoss中检查数据源?