diff --git a/app/models/Collection.test.ts b/app/models/Collection.test.ts index 9c4f97806f..b62150998f 100644 --- a/app/models/Collection.test.ts +++ b/app/models/Collection.test.ts @@ -20,4 +20,23 @@ describe("Collection model", () => { const shared = stores.collections.add({ id: "789", name: "Design" }); expect(shared.displayName).toBe("Design"); }); + + it("should not add a document that is already in the collection", () => { + const collection = stores.collections.add({ + id: "abc", + name: "Personal", + sort: { field: "title", direction: "asc" }, + documents: [], + }); + const document = stores.documents.add({ + id: "doc-1", + title: "Doc", + url: "/doc/doc-1", + collectionId: collection.id, + }); + + collection.addDocument(document); + collection.addDocument(document); + expect(collection.documents?.map((node) => node.id)).toEqual(["doc-1"]); + }); }); diff --git a/app/models/Collection.ts b/app/models/Collection.ts index 44e936ac66..b1f6aaf5f3 100644 --- a/app/models/Collection.ts +++ b/app/models/Collection.ts @@ -344,14 +344,15 @@ export default class Collection extends ParanoidModel { /** * Adds the document identified by the given id to the collection in - * memory. Does not add the document to the database or store. + * memory, if it is not already present. Does not add the document to the + * database or store. * * @param document The document to add. * @param parentDocumentId The id of the document to add the new document to. */ @action addDocument(document: Document, parentDocumentId?: string) { - if (!this.documents) { + if (!this.documents || this.childrenByDocumentId.has(document.id)) { return; } diff --git a/app/models/base/NavigableModel.ts b/app/models/base/NavigableModel.ts index 6edd3b4af9..a39b3bc1e0 100644 --- a/app/models/base/NavigableModel.ts +++ b/app/models/base/NavigableModel.ts @@ -128,14 +128,15 @@ export default abstract class NavigableModel extends Model { /** * Adds the document identified by the given id to the model in - * memory. Does not add the document to the database or store. + * memory, if it is not already present. Does not add the document to the + * database or store. * * @param document The document to add. * @param parentDocumentId The id of the document to add the new document to. */ @action addDocument(document: Document, parentDocumentId: string) { - if (!this.documents || !document || !parentDocumentId?.trim()) { + if (!this.documents || this.childrenByDocumentId.has(document.id)) { return; }