<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Easy way to insert data to MongoDB &#8211; Sibeesh Passion</title>
	<atom:link href="https://sibeeshpassion.com/tag/easy-way-to-insert-data-to-mongodb/feed/" rel="self" type="application/rss+xml" />
	<link>https://sibeeshpassion.com</link>
	<description>My passion towards life</description>
	<lastBuildDate>Tue, 10 Jul 2018 07:38:45 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>/wp-content/uploads/2017/04/Sibeesh_Passion_Logo_Small.png</url>
	<title>Easy way to insert data to MongoDB &#8211; Sibeesh Passion</title>
	<link>https://sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Using MongoDB on Node JS Application Using Mongoose</title>
		<link>https://sibeeshpassion.com/using-mongodb-on-node-js-application-using-mongoose/</link>
					<comments>https://sibeeshpassion.com/using-mongodb-on-node-js-application-using-mongoose/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sun, 03 Dec 2017 17:15:12 +0000</pubDate>
				<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[Node JS]]></category>
		<category><![CDATA[Easy way to insert data to MongoDB]]></category>
		<category><![CDATA[MongoDB with Mongoose]]></category>
		<category><![CDATA[Mongoose]]></category>
		<category><![CDATA[Node JS and MongoDB]]></category>
		<category><![CDATA[NPM]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=12589</guid>

					<description><![CDATA[[toc] Introduction In this post, we are going to see how we can use a MongoDB on our Node JS application with the help of the package Mongoose. We will also be covering some facts about MongoDB so that as a reader, you will understand why we had chosen MongoDB as our backend. We will be going through some steps to install the required packages using a node package manager terminal, so please be with me. At the end of this article, I guarantee that you will be proficient on how to connect a MongoDB in our Node JS application. [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h3>Introduction</h3>
<p>In this post, we are going to see how we can use a <a href="http://sibeeshpassion.com/category/MongoDB">MongoDB</a> on our Node JS application with the help of the package Mongoose. We will also be covering some facts about MongoDB so that as a reader, you will understand why we had chosen MongoDB as our backend. We will be going through some steps to install the required packages using a node package manager terminal, so please be with me. At the end of this article, I guarantee that you will be proficient on how to connect a MongoDB in our Node JS application. I hope you will like this article.</p>
<h3>Why MongoDB?</h3>
<p>Here, I am going to list down the reasons why I had chosen MongoDB.</p>
<ol>
<li>MongoDB is a NoSQL database when I say NoSQL, it means that it doesn&#8217;t have any structure to be followed.</li>
<li>There are no relationships, we can perform the relation using separate packages like Mongoose</li>
<li>Everything is JSON, even the data and collections are stored as JSON</li>
<li>Since the data is stored as JSON, no more conversions are needed. We can directly use it in our application.</li>
</ol>
<h3><span id="source-code">Source Code</span></h3>
<p>You can always clone or download the source code <a href="https://code.msdn.microsoft.com/Node-MongoDB-Mongoose-40fc3ad4">here</a></p>
<h3>Background</h3>
<p>Node JS has become a trend now, thus some most used databases. One of the recommended database for a Node application is MongoDB. As we discussed a MongoDB doesn&#8217;t have any structure inbuilt, here we are going to use a package called Mongoose, with that we can create some structure for our Database. Let&#8217;s just skip the talking and start developing.</p>
<h3>Setting up Node application</h3>
<p>To get started with the Node JS, create a folder and name as per your wish, this is going to be our project directory. Here I am going to use one of my favorite editor, Visual Studio Code. Now please point to your project container, and run the command below.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">npm init</pre>
<div id="attachment_12591" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/12/NPM-Init.png"><img fetchpriority="high" decoding="async" aria-describedby="caption-attachment-12591" class="size-full wp-image-12591" src="http://sibeeshpassion.com/wp-content/uploads/2017/12/NPM-Init.png" alt="NPM Init" width="634" height="449" srcset="/wp-content/uploads/2017/12/NPM-Init.png 504w, /wp-content/uploads/2017/12/NPM-Init-300x212.png 300w, /wp-content/uploads/2017/12/NPM-Init-400x283.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-12591" class="wp-caption-text">NPM Init</p></div>
<p>This will create a file named &#8220;Package.json&#8221; in your directory. We will be adding all of our dependencies in this file very soon. The command may ask you some default questions which you need to answer. If you need to create the package.json file with default values in it, you may consider running the below command.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">npm init --yes</pre>
<p>Let&#8217;s review our package.json file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">{
  "name": "node-mongodb-mongoose",
  "version": "1.0.0",
  "description": "A Node application with MongoDB and Mongoose",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" &amp;&amp; exit 1"
  },
  "keywords": [
    "Node",
    "Mongoose",
    "MongoDB"
  ],
  "author": "Sibeesh Venu",
  "license": "ISC"
}
</pre>
<h3>Getting the required packages</h3>
<p>Now that we have the application ready, let&#8217;s get the required packages ready.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">npm install --save mongoose</pre>
<p>This will create a new folder npm_modules on your project directory where you can see the package Mongoose in it.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">npm install --save express</pre>
<p>The above command will add the package express to our application.</p>
<h3>Creating the Node App</h3>
<p>Now we can create our server.js file where we are going to write most of our application code.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">var express = require("express")
var app = express()
app.listen("3010",()=&gt;{
    console.log("I just started listening!.")
})
</pre>
<p>Now run the command <code class="EnlighterJSRAW" data-enlighter-language="shell">node server.js</code>and make sure that you are getting a console as &#8221; I just started listening!.&#8221;.</p>
<p>If you are getting an error as preceding, please make sure that you are running the application on an unused port.</p>
<blockquote><p>PS F:\Visual Studio\Node.JS\Node-MongoDB-Mongoose&gt; node server.js<br />
events.js:136<br />
throw er; // Unhandled &#8216;error&#8217; event<br />
^</p>
<p>Error: listen EADDRINUSE :::3000<br />
at Object._errnoException (util.js:1031:13)<br />
at _exceptionWithHostPort (util.js:1052:20)<br />
at Server.setupListenHandle [as _listen2] (net.js:1367:14)<br />
at listenInCluster (net.js:1408:12)<br />
at Server.listen (net.js:1496:7)<br />
at Function.listen (F:\Visual Studio\Node.JS\Node-MongoDB-Mongoose\node_modules\express\lib\application.js:618:24)<br />
at Object.&lt;anonymous&gt; (F:\Visual Studio\Node.JS\Node-MongoDB-Mongoose\server.js:3:5)<br />
at Module._compile (module.js:641:30)<br />
at Object.Module._extensions..js (module.js:652:10)<br />
at Module.load (module.js:560:32)&#8221;</p></blockquote>
<h3>Setting up database</h3>
<p>Now that we have our application ready, let&#8217;s go and create our database. I am going to use mLab for creating the database. If you have not installed MongoDB on your machine, I strongly recommend creating a database in <a href="https://mlab.com/home">mLab.</a> I had created a database there and have got my connection string as preceding.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">mongodb://&lt;dbuser&gt;:&lt;dbpassword&gt;@ds038319.mlab.com:38319/mylearning</pre>
<p>We will be updating the connection string with actual DB user and password later. Please make sure that you are creating a user for your DB and remember the password.</p>
<h3>Creating a Mongoose model</h3>
<p>Let&#8217;s create a Mongoose model and set up our connection string now, which is going to be our collection. No worries, it is just a <a href="http://sibeeshpassion.com/category/JavaScript">JavaScript</a> model.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">var conString = "mongodb://admin:admin@ds038319.mlab.com:38319/mylearning"

/**
 * Models 
 */
var User = mongoose.model("User", {
    firstName: String,
    lastName: String
})</pre>
<blockquote><p>Please be noted that, when you move the codes to production, make sure that your password and user fields on the connection string are separated from this file and encrypted</p></blockquote>
<p>Now let&#8217;s connect our database.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">mongoose.connect(conString, { useMongoClient: true }, () =&gt; {
    console.log("DB is connected")
})</pre>
<h3>Setup the data</h3>
<p>We have our model ready, what else is needed now? Yes, you are right, we need data.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">var dummyUser = {
    firstName: "Sibeesh",
    lastName: "Venu"
}</pre>
<h3>Inserting the data into MongoDB</h3>
<p>We have got everything ready, we can insert the model now. Let&#8217;s do the saving logic now.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">mongoose.connect(conString, { useMongoClient: true }, () =&gt; {
    console.log("DB is connected")
    saveData()
})</pre>
<pre class="EnlighterJSRAW" data-enlighter-language="js">function saveData() {
    var user = new User(dummyUser);
    user.save();
}</pre>
<h3>Verify the data</h3>
<p>Once you run your application, go to your database and check for the entries there. I am sure there will be a new collection &#8220;User&#8221; and our inserted data. As I am using mLab database, here is how my data saved.</p>
<div id="attachment_12590" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/12/MongoDB-Data-Insertion.png"><img decoding="async" aria-describedby="caption-attachment-12590" class="size-full wp-image-12590" src="http://sibeeshpassion.com/wp-content/uploads/2017/12/MongoDB-Data-Insertion.png" alt="MongoDB Data Insertion" width="634" height="420" srcset="/wp-content/uploads/2017/12/MongoDB-Data-Insertion.png 539w, /wp-content/uploads/2017/12/MongoDB-Data-Insertion-300x199.png 300w, /wp-content/uploads/2017/12/MongoDB-Data-Insertion-400x265.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-12590" class="wp-caption-text">MongoDB Data Insertion</p></div>
<p>If you have noticed, you can see there are an another property names &#8220;_id&#8221; in our database collection. This is a unique id generated by MongoDB for us, so no need to think about it.</p>
<h3><em>Todo</em></h3>
<p>As the purpose of this article is to show how we can insert a data to MongoDB, I called the save method right after the database is connected. In our real life, this is not a recommended way. You must create an Ajax post request and handle the same. I am leaving that task to you. Please try to do that and let me know. I would love to hear back from you.</p>
<h3><span id="conclusion">Conclusion</span></h3>
<p>Thanks a lot for reading. Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h3><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h3>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/using-mongodb-on-node-js-application-using-mongoose/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
