DEV Community

Cover image for [Resolved] MongoDB Atlas line-break issue
Rahul Dahal
Rahul Dahal

Posted on

[Resolved] MongoDB Atlas line-break issue

The context

While creating this PWA, I wanted to store the markdown data into the MongoDB's Atlas.

Example Markdown

# Some interesting title
Description about the topic...

- list #1
- list #2

> Maybe a quote ?
Enter fullscreen mode Exit fullscreen mode

The above markdown would be stored as a single string in the database.

{
  // other fields
  markdown: "# Some interesting title\nDescription about the topic...\n- list #1\n- list #2\n> Maybe a quote ?"
  // further fields
}
Enter fullscreen mode Exit fullscreen mode

The problem

While reading the data from the Atlas, the line-break escape character, i.e. \n would come as already escaped, i.e. \\n notice the double '\'.

Therefore, while parsing it as HTML, the line-break wouldn't be read as a line-break character but a literal \n character.

Rendered HTML

Unexpected Render of Markdown

The Markdown parser(marked.js) expects a line-break between each block(headings, lists, paragraphs, quotes, etc) to render them as expected. Otherwise, it will render them as a single line of string.

In the example above, it renders everything as a heading level 1.

Why ?

When the Markdown parser sees # token, it assumes that the text after it(until a line-break) is to be rendered as a H₁. Thus, everything including lists, paragraphs, quotes are rendered as <h1> because of no line-break.

The Solution

I made a mistake by thinking that the problem was with the Markdown parser, while instead the problem was with the data coming from MongoDB.

The doubly escaped character \\n was the culprit.

As a workaround, I tried to replace all \\ns with \ns from the markdown string before passing it to the Markdown Parser.

import parser from "marked";

// 'markdownString' would be the markdown field read from mongodb
const replacedWithSingleEscape = markdownString.replace(/\\n/g, "\n");

parser(replacedWithSingleEscape);
Enter fullscreen mode Exit fullscreen mode

Solved! This is how the rendered output would look like after the fix

Expected Render of Markdown

Top comments (0)