{"id":12800,"date":"2014-04-07T12:29:03","date_gmt":"2014-04-07T06:59:03","guid":{"rendered":"http:\/\/www.tothenew.com\/blog\/?p=12800"},"modified":"2014-12-17T09:04:46","modified_gmt":"2014-12-17T03:34:46","slug":"getting-started-with-mongoose","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/getting-started-with-mongoose\/","title":{"rendered":"Getting started with Mongoose !!"},"content":{"rendered":"<p><strong>Mongoose<\/strong> is a <strong>Node.js<\/strong>\u00a0package that gives you an interface to play with mongo database. Mongoose has all sets of methods that help you to connect and access data stored in database.<br \/>\n It translates data from database in javaScript object which you  can provide to your application.<\/p>\n<blockquote><p>We will move step by step to know how it works.<\/p><\/blockquote>\n<p><strong>1.<\/strong> Requiring Mongoose<\/p>\n<pre><code><strong>\r\n1.1<\/strong> First install mongoose in your project using--&gt; npm install mongoose \r\n<strong>\r\n1.2<\/strong> var mongoose= require('mongoose'); <\/code><\/pre>\n<hr \/>\n<p><strong>2.<\/strong>Connecting To MongoDB<\/p>\n<pre><code>mongoose.connect('mongodb:\/\/localhost\/mydb'); <\/code><\/pre>\n<p>mongoose.connect is useful for making only a single db connection.<br \/>\nYou can get connection Instance by &#8211; <strong>var db=mongoose.connect;<\/strong><br \/>\n<strong>db <\/strong>object is used to listen the events attached to it.<\/p>\n<ul>\n<li>db.on(&#8216;connected&#8217;, function () {\/\/do the schema and query processing});<\/li>\n<li>db.on(&#8216;err&#8217;, function () {\/\/display error message});<\/li>\n<li>db.on(&#8216;disconnected&#8217;, function () {\/\/display db closed message});<\/li>\n<\/ul>\n<hr \/>\n<p><strong>3.<\/strong>Creating Schema<\/p>\n<pre><code>\r\nvar userSchema = new mongoose.Schema({ name: String, email: { type: String, unique: true }, createdOn:{ type: Date, 'default': Date.now } }); \r\n\/\/the above fields have been described in three ways <\/code><\/pre>\n<p><strong>schema <\/strong>is a way to describe structure of data in a database.<\/p>\n<ul>Schema accepts only the following types.<\/p>\n<li>String<\/li>\n<li>Number<\/li>\n<li>Date<\/li>\n<li>Boolean<\/li>\n<li>Buffer<\/li>\n<li>ObjectId<\/li>\n<li>Mixed<\/li>\n<li>Array<\/li>\n<\/ul>\n<hr \/>\n<p><strong>4.<\/strong>Creating model<\/p>\n<pre><code>\r\nvar User=mongoose.model( 'User', userSchema ); \r\n\/\/User --&gt; the name of model \r\n\/\/userSchema --&gt;&gt; the schema to be compiled \r\n<\/code><\/pre>\n<p><strong>model is -:: <\/strong><\/p>\n<ul>\n<li>A compiled version of the schema.<\/li>\n<li>maps directly to a single document in the database<\/li>\n<\/ul>\n<hr \/>\n<p><strong>5.<\/strong>Creating and Saving Instances<\/p>\n<pre><code>\r\nvar userObj1 = new User({ name: 'Ajay' });\r\nvar userObj2 = new User({ name: 'Raja',email:'mymail@gmail.com' }); \r\n<\/code><\/pre>\n<p><strong>these models can be saved in the database by ::-<\/strong><\/p>\n<ul>\n<li>userObj1.save(function(err){console.log(err);})<\/li>\n<li>userObj2.save(function(err){console.log(err);})<\/li>\n<\/ul>\n<hr \/>\n<p><strong>6.<\/strong> Reading from DB<br \/>\n<strong>We have two approaches to find or read data<\/strong><\/p>\n<ul>\n<li><strong>Using the QueryBuilder interface<\/strong><\/li>\n<\/ul>\n<pre><code>\r\nvar myQuery = User.find({'name' : 'Ajay'}); myQuery.where('age').gt(18);\r\nmyQuery.sort('age'); \r\nmyQuery.select('name email'); \r\nmyQuery.exec(function (err, userObjects){console.log(userObjects)});\r\n <\/code><\/pre>\n<ul>\n<li><strong>With a single command<\/strong><\/li>\n<\/ul>\n<pre><code>\r\n Model.find(conditions, [fields desired], [options], [callback]) \r\n \/\/ fields and options can be omitted \r\n User.find( {'name' : 'Ajay'},function (err,userObjects){ if (!err){console.log(userObjects);} }); <\/code><\/pre>\n<hr \/>\n<p><strong>7.<\/strong>Updating the DB<br \/>\n<strong>using findById<\/strong><\/p>\n<pre><code>\r\nUser.findById(id, function (err,UserObj) { if (!err) { UserObj.name = 'Amit'; UserObj.save(function(err)\r\n{ if (!err)console.log(\"saved successfully!!\");}); } }); <\/code><\/pre>\n<p><strong>the other way to do it-<\/strong><\/p>\n<pre><code> \r\nUser.update({ _id: id }, { $set: {name: 'Amit' }}, callback); <\/code><\/pre>\n<hr \/>\n<p><strong>8.<\/strong>Deleting from DB<br \/>\n<strong>using remove()<\/strong><\/p>\n<pre><code>\r\nUser.remove({ name :'Ajay' },callback); <\/code><\/pre>\n<p>So,these were certain set of steps which can be followed to use &#8220;mongoose&#8221; in your Node.js application.<br \/>\n<strong>Hope it helps!!<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Mongoose is a Node.js\u00a0package that gives you an interface to play with mongo database. Mongoose has all sets of methods that help you to connect and access data stored in database. It translates data from database in javaScript object which you can provide to your application. We will move step by step to know how [&hellip;]<\/p>\n","protected":false},"author":94,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":5},"categories":[1185],"tags":[1379,4843,4846,1316,1124],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/12800"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/94"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=12800"}],"version-history":[{"count":0,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/12800\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=12800"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=12800"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=12800"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}