How do I insert HTML into Mongodb?

2019-01-23 19:50发布

问题:

I keep getting kicked out of the shell when I try to paste in an HTML text file. How can this be done? Do I first need to use some javascript to encode it or something?

Example:

db.test.insert({x:"<div id='product-description'><p>Who hasn’t wished for a mini-Roomba to    handle the arduous task of cleaning their iPhone screen? Now your dreams have come true!</p>  <p>See the Takara web page for a <a href='http://www.takaratomy.co.jp/products/automee/'  title='automee s' target='_blank'>demo video.</a></p>
<p><strong>Colors: </strong> White, Red, Orange and Blue<br>
Runs on a single AA battery.</p>
<p>1,575 yen</p><!-- end #product-description --></div>"})

EDIT

I put only single quotes inside my html and wrapped the whole thing in double-quotes, but still no good. shell error:

> j = ({z:"<div id='product-description'><p>Who hasn
---
Unicode text could not be correctly displayed.
Please change your console font to a Unicode font (e.g. Lucida Console).
---

’
bye

回答1:

You need to remove or encode the control characters in your string.

For example, paste your text in here, and encode to UTF-8 ECMAScript (which means javascript strings).

ps: here an article about strings in javascript. tells you what needs escaping. http://docstore.mik.ua/orelly/webprog/jscript/ch03_02.htm



回答2:

rompetroll provided some good references to get started. I too found a good solution online which works fine:

Link

But I think there is still some confusion regarding "displaying html back to browser from db". So, following are the steps which removes this confusion :

Step 1: Store html in mongodb

Mongo store everything in form of object. Basically convert your html into utf-8 or ASCII complied string and then store it to mongo.

<div>hi!</div> [from]

&lt;div&gt;hi!&lt;/div&gt; [to UTF-8]

Step 2: Display html to browser

This is the step which is the source of confusion to some. People often forget to convert string back to html before displaying it to browser. You have to decode your html using the same method you used for encoding.

&lt;div&gt;hi!&lt;/div&gt; [output from mongo (decode it to html)]

<div>hi!</div> [browser output of above string]

(browser will read it as string and display as it is and not html(hi!) and hence needs to be decoded)

Link that I have provided have reference for both the steps.

Hope this will help

Cheers :)