|
|
@@ -70,9 +70,10 @@ class PageTagRelation {
|
|
|
return { data: tags, totalCount };
|
|
|
}
|
|
|
|
|
|
- static async findByPageId(pageId) {
|
|
|
- const relations = await this.find({ relatedPage: pageId }).populate('relatedTag').select('-_id relatedTag');
|
|
|
- return relations.filter((relation) => { return relation.relatedTag !== null });
|
|
|
+ static async findByPageId(pageId, options = {}) {
|
|
|
+ const isAcceptRelatedTagNull = options.nullable || null;
|
|
|
+ const relations = await this.find({ relatedPage: pageId }).populate('relatedTag').select('relatedTag');
|
|
|
+ return isAcceptRelatedTagNull ? relations : relations.filter((relation) => { return relation.relatedTag !== null });
|
|
|
}
|
|
|
|
|
|
static async listTagNamesByPage(pageId) {
|
|
|
@@ -138,17 +139,23 @@ class PageTagRelation {
|
|
|
const Tag = mongoose.model('Tag');
|
|
|
|
|
|
// get relations for this page
|
|
|
- const relations = await this.findByPageId(pageId);
|
|
|
-
|
|
|
- // unlink relations
|
|
|
- const unlinkTagRelations = relations.filter((relation) => { return !tags.includes(relation.relatedTag.name) });
|
|
|
- const bulkDeletePromise = this.deleteMany({
|
|
|
- relatedPage: pageId,
|
|
|
- relatedTag: { $in: unlinkTagRelations.map((relation) => { return relation.relatedTag._id }) },
|
|
|
+ const relations = await this.findByPageId(pageId, { nullable: true });
|
|
|
+
|
|
|
+ const unlinkTagRelationIds = [];
|
|
|
+ const relatedTagNames = [];
|
|
|
+
|
|
|
+ relations.forEach((relation) => {
|
|
|
+ if (relation.relatedTag == null) {
|
|
|
+ unlinkTagRelationIds.push(relation._id);
|
|
|
+ }
|
|
|
+ else {
|
|
|
+ relatedTagNames.push(relation.relatedTag.name);
|
|
|
+ if (!tags.includes(relation.relatedTag.name)) {
|
|
|
+ unlinkTagRelationIds.push(relation._id);
|
|
|
+ }
|
|
|
+ }
|
|
|
});
|
|
|
-
|
|
|
- // filter tags to create
|
|
|
- const relatedTagNames = relations.map((relation) => { return relation.relatedTag.name });
|
|
|
+ const bulkDeletePromise = this.deleteMany({ _id: { $in: unlinkTagRelationIds } });
|
|
|
// find or create tags
|
|
|
const tagsToCreate = tags.filter((tag) => { return !relatedTagNames.includes(tag) });
|
|
|
const tagEntities = await Tag.findOrCreateMany(tagsToCreate);
|