{"id":8138,"date":"2016-05-28T04:42:00","date_gmt":"2016-05-28T04:42:00","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2015\/11\/28\/automattic-mongoose\/"},"modified":"2022-08-30T15:23:53","modified_gmt":"2022-08-30T15:23:53","slug":"automattic-mongoose","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2016\/05\/28\/automattic-mongoose\/","title":{"rendered":"Automattic\/mongoose"},"content":{"rendered":"<p>Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment.<\/p>\n<p><img decoding=\"async\" src=\"http:\/\/api.travis-ci.org\/Automattic\/mongoose.png?branch=master\"> <img decoding=\"async\" src=\"http:\/\/badges.gitter.im\/Join%20Chat.svg\"><\/p>\n<h2>Documentation<\/h2>\n<p>mongoosejs.com<\/p>\n<h2>Support<\/h2>\n<h2>Plugins<\/h2>\n<p>Check out the plugins search site to see hundreds of related modules from the community.<\/p>\n<p>Build your own Mongoose plugin through generator-mongoose-plugin.<\/p>\n<h2>Contributors<\/h2>\n<p>View all 100+ contributors. Stand up and be counted as a contributor too!<\/p>\n<h2>Live Examples<\/h2>\n<p><img decoding=\"async\" src=\"http:\/\/runnable.com\/external\/styles\/assets\/runnablebtn.png\"><\/p>\n<h2>Installation<\/h2>\n<p>First install node.js and mongodb. Then:<\/p>\n<pre><code>$ npm install mongoose\n<\/code><\/pre>\n<h2>Stability<\/h2>\n<p>The current stable branch is master. The 3.8.x branch is for legacy support for the 3.x release series, which will continue to be maintained until September 1, 2015.<\/p>\n<h2>Overview<\/h2>\n<h3>Connecting to MongoDB<\/h3>\n<p>First, we need to define a connection. If your app uses only one database, you should use <code>mongoose.connect<\/code>. If you need to create additional connections, use <code>mongoose.createConnection<\/code>.<\/p>\n<p>Both <code>connect<\/code> and <code>createConnection<\/code> take a <code>mongodb:\/\/<\/code> URI, or the parameters <code>host, database, port, options<\/code>.<\/p>\n<pre><code>var mongoose = require('mongoose');\n\nmongoose.connect('mongodb:\/\/localhost\/my_database');\n<\/code><\/pre>\n<p>Once connected, the <code>open<\/code> event is fired on the <code>Connection<\/code> instance. If you\u2019re using <code>mongoose.connect<\/code>, the <code>Connection<\/code> is <code>mongoose.connection<\/code>. Otherwise, <code>mongoose.createConnection<\/code> return value is a <code>Connection<\/code>.<\/p>\n<p><strong>Note:<\/strong> <em>If the local connection fails then try using 127.0.0.1 instead of localhost. Sometimes issues may arise when the local hostname has been changed.<\/em><\/p>\n<p><strong>Important!<\/strong> Mongoose buffers all the commands until it\u2019s connected to the database. This means that you don\u2019t have to wait until it connects to MongoDB in order to define models, run queries, etc.<\/p>\n<h3>Defining a Model<\/h3>\n<p>Models are defined through the <code>Schema<\/code> interface.<\/p>\n<pre><code>var Schema = mongoose.Schema\n  , ObjectId = Schema.ObjectId;\n\nvar BlogPost = new Schema({\n    author    : ObjectId\n  , title     : String\n  , body      : String\n  , date      : Date\n});\n<\/code><\/pre>\n<p>Aside from defining the structure of your documents and the types of data you\u2019re storing, a Schema handles the definition of:<\/p>\n<p>The following example shows some of these features:<\/p>\n<pre><code>var Comment = new Schema({\n    name  :  { type: String, default: 'hahaha' }\n  , age   :  { type: Number, min: 18, index: true }\n  , bio   :  { type: String, match: \/[a-z]\/ }\n  , date  :  { type: Date, default: Date.now }\n  , buff  :  Buffer\n});\n\n\/\/ a setter\nComment.path('name').set(function (v) {\n  return capitalize(v);\n});\n\n\/\/ middleware\nComment.pre('save', function (next) {\n  notify(this.get('email'));\n  next();\n});\n<\/code><\/pre>\n<p>Take a look at the example in <code>examples\/schema.js<\/code> for an end-to-end example of a typical setup.<\/p>\n<h3>Accessing a Model<\/h3>\n<p>Once we define a model through <code>mongoose.model('ModelName', mySchema)<\/code>, we can access it through the same function<\/p>\n<pre><code>var myModel = mongoose.model('ModelName');\n<\/code><\/pre>\n<p>Or just do it all at once<\/p>\n<pre><code>var MyModel = mongoose.model('ModelName', mySchema);\n<\/code><\/pre>\n<p>The first argument is the <em>singular<\/em> name of the collection your model is for. <strong>Mongoose automatically looks for the <em>plural<\/em> version of your model name.<\/strong> For example, if you use<\/p>\n<pre><code>var MyModel = mongoose.model('Ticket', mySchema);\n<\/code><\/pre>\n<p>Then Mongoose will create the model for your <strong>tickets<\/strong> collection, not your <strong>ticket<\/strong> collection.<\/p>\n<p>Once we have our model, we can then instantiate it, and save it:<\/p>\n<pre><code>var instance = new MyModel();\ninstance.my.key = 'hello';\ninstance.save(function (err) {\n  \/\/\n});\n<\/code><\/pre>\n<p>Or we can find documents from the same collection<\/p>\n<pre><code>MyModel.find({}, function (err, docs) {\n  \/\/ docs.forEach\n});\n<\/code><\/pre>\n<p>You can also <code>findOne<\/code>, <code>findById<\/code>, <code>update<\/code>, etc. For more details check out the docs.<\/p>\n<p><strong>Important!<\/strong> If you opened a separate connection using <code>mongoose.createConnection()<\/code> but attempt to access the model through <code>mongoose.model('ModelName')<\/code> it will not work as expected since it is not hooked up to an active db connection. In this case access your model through the connection you created:<\/p>\n<pre><code>var conn = mongoose.createConnection('your connection string')\n  , MyModel = conn.model('ModelName', schema)\n  , m = new MyModel;\nm.save(); \/\/ works\n<\/code><\/pre>\n<p>vs<\/p>\n<pre><code>var conn = mongoose.createConnection('your connection string')\n  , MyModel = mongoose.model('ModelName', schema)\n  , m = new MyModel;\nm.save(); \/\/ does not work b\/c the default connection object was never connected\n<\/code><\/pre>\n<h3>Embedded Documents<\/h3>\n<p>In the first example snippet, we defined a key in the Schema that looks like:<\/p>\n<pre><code>comments: [Comments]\n<\/code><\/pre>\n<p>Where <code>Comments<\/code> is a <code>Schema<\/code> we created. This means that creating embedded documents is as simple as:<\/p>\n<pre><code>\/\/ retrieve my model\nvar BlogPost = mongoose.model('BlogPost');\n\n\/\/ create a blog post\nvar post = new BlogPost();\n\n\/\/ create a comment\npost.comments.push({ title: 'My comment' });\n\npost.save(function (err) {\n  if (!err) console.log('Success!');\n});\n<\/code><\/pre>\n<p>The same goes for removing them:<\/p>\n<pre><code>BlogPost.findById(myId, function (err, post) {\n  if (!err) {\n    post.comments[0].remove();\n    post.save(function (err) {\n      \/\/ do something\n    });\n  }\n});\n<\/code><\/pre>\n<p>Embedded documents enjoy all the same features as your models. Defaults, validators, middleware. Whenever an error occurs, it\u2019s bubbled to the <code>save()<\/code> error callback, so error handling is a snap!<\/p>\n<p>Mongoose interacts with your embedded documents in arrays <em>atomically<\/em>, out of the box.<\/p>\n<h3>Middleware<\/h3>\n<p>See the docs page.<\/p>\n<h4>Intercepting and mutating method arguments<\/h4>\n<p>You can intercept method arguments via middleware.<\/p>\n<p>For example, this would allow you to broadcast changes about your Documents every time someone <code>set<\/code>s a path in your Document to a new value:<\/p>\n<pre><code>schema.pre('set', function (next, path, val, typel) {\n  \/\/ `this` is the current Document\n  this.emit('set', path, val);\n\n  \/\/ Pass control to the next pre\n  next();\n});\n<\/code><\/pre>\n<p>Moreover, you can mutate the incoming <code>method<\/code> arguments so that subsequent middleware see different values for those arguments. To do so, just pass the new values to <code>next<\/code>:<\/p>\n<pre><code>.pre(method, function firstPre (next, methodArg1, methodArg2) {\n  \/\/ Mutate methodArg1\n  next(\"altered-\" + methodArg1.toString(), methodArg2);\n});\n\n\/\/ pre declaration is chainable\n.pre(method, function secondPre (next, methodArg1, methodArg2) {\n  console.log(methodArg1);\n  \/\/ =&gt; 'altered-originalValOfMethodArg1'\n\n  console.log(methodArg2);\n  \/\/ =&gt; 'originalValOfMethodArg2'\n\n  \/\/ Passing no arguments to `next` automatically passes along the current argument values\n  \/\/ i.e., the following `next()` is equivalent to `next(methodArg1, methodArg2)`\n  \/\/ and also equivalent to, with the example method arg\n  \/\/ values, `next('altered-originalValOfMethodArg1', 'originalValOfMethodArg2')`\n  next();\n});\n<\/code><\/pre>\n<h4>Schema gotcha<\/h4>\n<p><code>type<\/code>, when used in a schema has special meaning within Mongoose. If your schema requires using <code>type<\/code> as a nested property you must use object notation:<\/p>\n<pre><code>new Schema({\n    broken: { type: Boolean }\n  , asset : {\n        name: String\n      , type: String \/\/ uh oh, it broke. asset will be interpreted as String\n    }\n});\n\nnew Schema({\n    works: { type: Boolean }\n  , asset : {\n        name: String\n      , type: { type: String } \/\/ works. asset is an object with a type property\n    }\n});\n<\/code><\/pre>\n<h3>Driver access<\/h3>\n<p>The driver being used defaults to node-mongodb-native and is directly accessible through <code>YourModel.collection<\/code>. <strong>Note<\/strong>: using the driver directly bypasses all Mongoose power-tools like validation, getters, setters, hooks, etc.<\/p>\n<h2>API Docs<\/h2>\n<p>Find the API docs here, generated using dox and acquit.<\/p>\n<h2>License<\/h2>\n<p>Copyright \u00a9 2010 LearnBoost<\/p>\n<p>Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \u2018Software\u2019), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:<\/p>\n<p>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.<\/p>\n<p>THE SOFTWARE IS PROVIDED \u2018AS IS\u2019, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Documentation mongoosejs.com Support Plugins Check out the plugins search site to see hundreds of related modules from the community. Build your own Mongoose plugin through generator-mongoose-plugin. Contributors View all 100+ contributors. Stand up and be counted as a contributor too! Live [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-8138","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/8138","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=8138"}],"version-history":[{"count":2,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/8138\/revisions"}],"predecessor-version":[{"id":8732,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/8138\/revisions\/8732"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=8138"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=8138"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=8138"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}