Skip to content

Commit e86be85

Browse files
committed
fix(post,slug-tracker): correct ObjectId vs string comparisons
trackSlugChanges, updateById's category check, and checkRelated were comparing mongoose ObjectId instances against string ids from request bodies with === / !==, which is always false. The tracker bug produced 89 redundant slug_trackers in production; the related-check silently disabled the self-relation guard. Switch to String()-normalized comparisons, and harden createTracker to upsert on (slug, type, targetId) so future regressions cannot duplicate.
1 parent 3ee50fd commit e86be85

2 files changed

Lines changed: 10 additions & 4 deletions

File tree

apps/core/src/modules/post/post.service.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,7 @@ export class PostService implements OnApplicationBootstrap {
176176
}
177177
if (
178178
newDocument.categoryId &&
179-
oldDocument.categoryId !== newDocument.categoryId
179+
String(oldDocument.categoryId) !== String(newDocument.categoryId)
180180
) {
181181
return trackSlugChanges()
182182
}
@@ -269,7 +269,7 @@ export class PostService implements OnApplicationBootstrap {
269269

270270
// 看看 category 改了没
271271
const { categoryId } = data
272-
if (categoryId && categoryId !== oldDocument.categoryId) {
272+
if (categoryId && String(categoryId) !== String(oldDocument.categoryId)) {
273273
const category = await this.categoryService.findCategoryById(
274274
categoryId as any as string,
275275
)
@@ -430,7 +430,7 @@ export class PostService implements OnApplicationBootstrap {
430430
}
431431

432432
return relatedPosts.map((i) => {
433-
if (i.related && (i.related as string[]).includes(data.id!)) {
433+
if (i.related?.some((rel) => String(rel) === data.id)) {
434434
throw new BizException(ErrorCodeEnum.PostSelfRelation)
435435
}
436436
return i.id

apps/core/src/modules/slug-tracker/slug-tracker.service.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import { Injectable } from '@nestjs/common'
22
import type { ReturnModelType } from '@typegoose/typegoose'
3+
34
import type { ArticleTypeEnum } from '~/constants/article.constant'
45
import { InjectModel } from '~/transformers/model.transformer'
6+
57
import { SlugTrackerModel } from './slug-tracker.model'
68

79
@Injectable()
@@ -12,7 +14,11 @@ export class SlugTrackerService {
1214
) {}
1315

1416
createTracker(slug: string, type: ArticleTypeEnum, targetId: string) {
15-
return this.slugTrackerModel.create({ slug, type, targetId })
17+
return this.slugTrackerModel.updateOne(
18+
{ slug, type, targetId },
19+
{ $setOnInsert: { slug, type, targetId } },
20+
{ upsert: true },
21+
)
1622
}
1723

1824
findTrackerBySlug(slug: string, type: ArticleTypeEnum) {

0 commit comments

Comments
 (0)