问题描述
我正在尝试将我的 Nodejs Express 应用程序转换为 Loopback 4,但我不知道如何增加计数器.在我的 Angular 9 应用程序中,当用户单击图标时,计数器会增加.这在 Express 中完美运行
I'm trying to convert my Nodejs Express app to Loopback 4 and I can't figure out how to increment a counter. In my Angular 9 app when a user clicks an icon a counter is incremented. This works perfectly in 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.
I tried to first get the value of counter and then increment but every time I save VS Code reformats the code in an an unusual way. In this snippet I commented out the line of code that causes this reformatting. I can set the counter value, e.g. 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 } }
?
How do I implement { $inc: { counter: 1 } }
in 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);
}
推荐答案
你可以使用 mongo 更新运算符.
You can use the mongo update-operators.
基本上,您只需在 MongoDB 数据源定义中设置 allowExtendedOperators=true
(指南).之后就可以直接使用这些运算符了.
Basically, you just have to set allowExtendedOperators=true
at your MongoDB datasource definition (guide). After that, you can directly use these operators.
使用示例:
// increment icon.counter by 3
await this.iconsRepository.updateById(id, {$inc: {counter: 3}} as Partial<Counter>);
目前,lb4 类型中缺少这些运算符,因此您必须欺骗打字稿才能接受它们.这很丑陋,但这是我现在能找到的唯一解决方案.
Currently, these operators are missing from the lb4 types so you must cheat typescript to accept them. It's ugly but that's the only solution I could find right now.
你可以关注这个问题看看发生了什么这些运算符.
You can follow this issue to see what's going on with these operators.
这篇关于如何使用 MongoDB 数据源在 LoopBack 4 中增加计数器变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!