1 | # Mongoose
|
2 |
|
3 | Mongoose is a [MongoDB](https://www.mongodb.org/) object modeling tool designed to work in an asynchronous environment. Mongoose supports [Node.js](https://nodejs.org/en/) and [Deno](https://deno.land/) (alpha).
|
4 |
|
5 | [![Build Status](https://github.com/Automattic/mongoose/workflows/Test/badge.svg)](https://github.com/Automattic/mongoose)
|
6 | [![NPM version](https://badge.fury.io/js/mongoose.svg)](http://badge.fury.io/js/mongoose)
|
7 | [![Deno version](https://deno.land/badge/mongoose/version)](https://deno.land/x/mongoose)
|
8 | [![Deno popularity](https://deno.land/badge/mongoose/popularity)](https://deno.land/x/mongoose)
|
9 |
|
10 | [![npm](https://nodei.co/npm/mongoose.png)](https://www.npmjs.com/package/mongoose)
|
11 |
|
12 | ## Documentation
|
13 |
|
14 | The official documentation website is [mongoosejs.com](http://mongoosejs.com/).
|
15 |
|
16 | Mongoose 8.0.0 was released on October 31, 2023. You can find more details on [backwards breaking changes in 8.0.0 on our docs site](https://mongoosejs.com/docs/migrating_to_8.html).
|
17 |
|
18 | ## Support
|
19 |
|
20 | * [Stack Overflow](http://stackoverflow.com/questions/tagged/mongoose)
|
21 | * [Bug Reports](https://github.com/Automattic/mongoose/issues/)
|
22 | * [Mongoose Slack Channel](http://slack.mongoosejs.io/)
|
23 | * [Help Forum](http://groups.google.com/group/mongoose-orm)
|
24 | * [MongoDB Support](https://www.mongodb.com/docs/manual/support/)
|
25 |
|
26 | ## Plugins
|
27 |
|
28 | Check out the [plugins search site](http://plugins.mongoosejs.io/) to see hundreds of related modules from the community. Next, learn how to write your own plugin from the [docs](http://mongoosejs.com/docs/plugins.html) or [this blog post](http://thecodebarbarian.com/2015/03/06/guide-to-mongoose-plugins).
|
29 |
|
30 | ## Contributors
|
31 |
|
32 | Pull requests are always welcome! Please base pull requests against the `master`
|
33 | branch and follow the [contributing guide](https://github.com/Automattic/mongoose/blob/master/CONTRIBUTING.md).
|
34 |
|
35 | If your pull requests makes documentation changes, please do **not**
|
36 | modify any `.html` files. The `.html` files are compiled code, so please make
|
37 | your changes in `docs/*.pug`, `lib/*.js`, or `test/docs/*.js`.
|
38 |
|
39 | View all 400+ [contributors](https://github.com/Automattic/mongoose/graphs/contributors).
|
40 |
|
41 | ## Installation
|
42 |
|
43 | First install [Node.js](http://nodejs.org/) and [MongoDB](https://www.mongodb.org/downloads). Then:
|
44 |
|
45 | ```sh
|
46 | npm install mongoose
|
47 | ```
|
48 |
|
49 | Mongoose 6.8.0 also includes alpha support for [Deno](https://deno.land/).
|
50 |
|
51 | ## Importing
|
52 |
|
53 | ```javascript
|
54 | // Using Node.js `require()`
|
55 | const mongoose = require('mongoose');
|
56 |
|
57 | // Using ES6 imports
|
58 | import mongoose from 'mongoose';
|
59 | ```
|
60 |
|
61 | Or, using [Deno's `createRequire()` for CommonJS support](https://deno.land/std@0.113.0/node/README.md?source=#commonjs-modules-loading) as follows.
|
62 |
|
63 | ```javascript
|
64 | import { createRequire } from 'https://deno.land/std@0.177.0/node/module.ts';
|
65 | const require = createRequire(import.meta.url);
|
66 |
|
67 | const mongoose = require('mongoose');
|
68 |
|
69 | mongoose.connect('mongodb://127.0.0.1:27017/test')
|
70 | .then(() => console.log('Connected!'));
|
71 | ```
|
72 |
|
73 | You can then run the above script using the following.
|
74 |
|
75 | ```sh
|
76 | deno run --allow-net --allow-read --allow-sys --allow-env mongoose-test.js
|
77 | ```
|
78 |
|
79 | ## Mongoose for Enterprise
|
80 |
|
81 | Available as part of the Tidelift Subscription
|
82 |
|
83 | The maintainers of mongoose and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-mongoose?utm_source=npm-mongoose&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
|
84 |
|
85 | ## Overview
|
86 |
|
87 | ### Connecting to MongoDB
|
88 |
|
89 | First, we need to define a connection. If your app uses only one database, you should use `mongoose.connect`. If you need to create additional connections, use `mongoose.createConnection`.
|
90 |
|
91 | Both `connect` and `createConnection` take a `mongodb://` URI, or the parameters `host, database, port, options`.
|
92 |
|
93 | ```js
|
94 | await mongoose.connect('mongodb://127.0.0.1/my_database');
|
95 | ```
|
96 |
|
97 | Once connected, the `open` event is fired on the `Connection` instance. If you're using `mongoose.connect`, the `Connection` is `mongoose.connection`. Otherwise, `mongoose.createConnection` return value is a `Connection`.
|
98 |
|
99 | **Note:** *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.*
|
100 |
|
101 | **Important!** Mongoose buffers all the commands until it's connected to the database. This means that you don't have to wait until it connects to MongoDB in order to define models, run queries, etc.
|
102 |
|
103 | ### Defining a Model
|
104 |
|
105 | Models are defined through the `Schema` interface.
|
106 |
|
107 | ```js
|
108 | const Schema = mongoose.Schema;
|
109 | const ObjectId = Schema.ObjectId;
|
110 |
|
111 | const BlogPost = new Schema({
|
112 | author: ObjectId,
|
113 | title: String,
|
114 | body: String,
|
115 | date: Date
|
116 | });
|
117 | ```
|
118 |
|
119 | Aside from defining the structure of your documents and the types of data you're storing, a Schema handles the definition of:
|
120 |
|
121 | * [Validators](http://mongoosejs.com/docs/validation.html) (async and sync)
|
122 | * [Defaults](http://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-default)
|
123 | * [Getters](http://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-get)
|
124 | * [Setters](http://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-set)
|
125 | * [Indexes](http://mongoosejs.com/docs/guide.html#indexes)
|
126 | * [Middleware](http://mongoosejs.com/docs/middleware.html)
|
127 | * [Methods](http://mongoosejs.com/docs/guide.html#methods) definition
|
128 | * [Statics](http://mongoosejs.com/docs/guide.html#statics) definition
|
129 | * [Plugins](http://mongoosejs.com/docs/plugins.html)
|
130 | * [pseudo-JOINs](http://mongoosejs.com/docs/populate.html)
|
131 |
|
132 | The following example shows some of these features:
|
133 |
|
134 | ```js
|
135 | const Comment = new Schema({
|
136 | name: { type: String, default: 'hahaha' },
|
137 | age: { type: Number, min: 18, index: true },
|
138 | bio: { type: String, match: /[a-z]/ },
|
139 | date: { type: Date, default: Date.now },
|
140 | buff: Buffer
|
141 | });
|
142 |
|
143 | // a setter
|
144 | Comment.path('name').set(function(v) {
|
145 | return capitalize(v);
|
146 | });
|
147 |
|
148 | // middleware
|
149 | Comment.pre('save', function(next) {
|
150 | notify(this.get('email'));
|
151 | next();
|
152 | });
|
153 | ```
|
154 |
|
155 | Take a look at the example in [`examples/schema/schema.js`](https://github.com/Automattic/mongoose/blob/master/examples/schema/schema.js) for an end-to-end example of a typical setup.
|
156 |
|
157 | ### Accessing a Model
|
158 |
|
159 | Once we define a model through `mongoose.model('ModelName', mySchema)`, we can access it through the same function
|
160 |
|
161 | ```js
|
162 | const MyModel = mongoose.model('ModelName');
|
163 | ```
|
164 |
|
165 | Or just do it all at once
|
166 |
|
167 | ```js
|
168 | const MyModel = mongoose.model('ModelName', mySchema);
|
169 | ```
|
170 |
|
171 | The first argument is the *singular* name of the collection your model is for. **Mongoose automatically looks for the *plural* version of your model name.** For example, if you use
|
172 |
|
173 | ```js
|
174 | const MyModel = mongoose.model('Ticket', mySchema);
|
175 | ```
|
176 |
|
177 | Then `MyModel` will use the **tickets** collection, not the **ticket** collection. For more details read the [model docs](https://mongoosejs.com/docs/api/mongoose.html#mongoose_Mongoose-model).
|
178 |
|
179 | Once we have our model, we can then instantiate it, and save it:
|
180 |
|
181 | ```js
|
182 | const instance = new MyModel();
|
183 | instance.my.key = 'hello';
|
184 | await instance.save();
|
185 | ```
|
186 |
|
187 | Or we can find documents from the same collection
|
188 |
|
189 | ```js
|
190 | await MyModel.find({});
|
191 | ```
|
192 |
|
193 | You can also `findOne`, `findById`, `update`, etc.
|
194 |
|
195 | ```js
|
196 | const instance = await MyModel.findOne({ /* ... */ });
|
197 | console.log(instance.my.key); // 'hello'
|
198 | ```
|
199 |
|
200 | For more details check out [the docs](http://mongoosejs.com/docs/queries.html).
|
201 |
|
202 | **Important!** If you opened a separate connection using `mongoose.createConnection()` but attempt to access the model through `mongoose.model('ModelName')` 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:
|
203 |
|
204 | ```js
|
205 | const conn = mongoose.createConnection('your connection string');
|
206 | const MyModel = conn.model('ModelName', schema);
|
207 | const m = new MyModel();
|
208 | await m.save(); // works
|
209 | ```
|
210 |
|
211 | vs
|
212 |
|
213 | ```js
|
214 | const conn = mongoose.createConnection('your connection string');
|
215 | const MyModel = mongoose.model('ModelName', schema);
|
216 | const m = new MyModel();
|
217 | await m.save(); // does not work b/c the default connection object was never connected
|
218 | ```
|
219 |
|
220 | ### Embedded Documents
|
221 |
|
222 | In the first example snippet, we defined a key in the Schema that looks like:
|
223 |
|
224 | ```txt
|
225 | comments: [Comment]
|
226 | ```
|
227 |
|
228 | Where `Comment` is a `Schema` we created. This means that creating embedded documents is as simple as:
|
229 |
|
230 | ```js
|
231 | // retrieve my model
|
232 | const BlogPost = mongoose.model('BlogPost');
|
233 |
|
234 | // create a blog post
|
235 | const post = new BlogPost();
|
236 |
|
237 | // create a comment
|
238 | post.comments.push({ title: 'My comment' });
|
239 |
|
240 | await post.save();
|
241 | ```
|
242 |
|
243 | The same goes for removing them:
|
244 |
|
245 | ```js
|
246 | const post = await BlogPost.findById(myId);
|
247 | post.comments[0].deleteOne();
|
248 | await post.save();
|
249 | ```
|
250 |
|
251 | Embedded documents enjoy all the same features as your models. Defaults, validators, middleware.
|
252 |
|
253 | ### Middleware
|
254 |
|
255 | See the [docs](http://mongoosejs.com/docs/middleware.html) page.
|
256 |
|
257 | #### Intercepting and mutating method arguments
|
258 |
|
259 | You can intercept method arguments via middleware.
|
260 |
|
261 | For example, this would allow you to broadcast changes about your Documents every time someone `set`s a path in your Document to a new value:
|
262 |
|
263 | ```js
|
264 | schema.pre('set', function(next, path, val, typel) {
|
265 | // `this` is the current Document
|
266 | this.emit('set', path, val);
|
267 |
|
268 | // Pass control to the next pre
|
269 | next();
|
270 | });
|
271 | ```
|
272 |
|
273 | Moreover, you can mutate the incoming `method` arguments so that subsequent middleware see different values for those arguments. To do so, just pass the new values to `next`:
|
274 |
|
275 | ```js
|
276 | schema.pre(method, function firstPre(next, methodArg1, methodArg2) {
|
277 | // Mutate methodArg1
|
278 | next('altered-' + methodArg1.toString(), methodArg2);
|
279 | });
|
280 |
|
281 | // pre declaration is chainable
|
282 | schema.pre(method, function secondPre(next, methodArg1, methodArg2) {
|
283 | console.log(methodArg1);
|
284 | // => 'altered-originalValOfMethodArg1'
|
285 |
|
286 | console.log(methodArg2);
|
287 | // => 'originalValOfMethodArg2'
|
288 |
|
289 | // Passing no arguments to `next` automatically passes along the current argument values
|
290 | // i.e., the following `next()` is equivalent to `next(methodArg1, methodArg2)`
|
291 | // and also equivalent to, with the example method arg
|
292 | // values, `next('altered-originalValOfMethodArg1', 'originalValOfMethodArg2')`
|
293 | next();
|
294 | });
|
295 | ```
|
296 |
|
297 | #### Schema gotcha
|
298 |
|
299 | `type`, when used in a schema has special meaning within Mongoose. If your schema requires using `type` as a nested property you must use object notation:
|
300 |
|
301 | ```js
|
302 | new Schema({
|
303 | broken: { type: Boolean },
|
304 | asset: {
|
305 | name: String,
|
306 | type: String // uh oh, it broke. asset will be interpreted as String
|
307 | }
|
308 | });
|
309 |
|
310 | new Schema({
|
311 | works: { type: Boolean },
|
312 | asset: {
|
313 | name: String,
|
314 | type: { type: String } // works. asset is an object with a type property
|
315 | }
|
316 | });
|
317 | ```
|
318 |
|
319 | ### Driver Access
|
320 |
|
321 | Mongoose is built on top of the [official MongoDB Node.js driver](https://github.com/mongodb/node-mongodb-native). Each mongoose model keeps a reference to a [native MongoDB driver collection](http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html). The collection object can be accessed using `YourModel.collection`. However, using the collection object directly bypasses all mongoose features, including hooks, validation, etc. The one
|
322 | notable exception that `YourModel.collection` still buffers
|
323 | commands. As such, `YourModel.collection.find()` will **not**
|
324 | return a cursor.
|
325 |
|
326 | ## API Docs
|
327 |
|
328 | Find the API docs [here](http://mongoosejs.com/docs/api/mongoose.html), generated using [dox](https://github.com/tj/dox)
|
329 | and [acquit](https://github.com/vkarpov15/acquit).
|
330 |
|
331 | ## Related Projects
|
332 |
|
333 | ### MongoDB Runners
|
334 |
|
335 | * [run-rs](https://www.npmjs.com/package/run-rs)
|
336 | * [mongodb-memory-server](https://www.npmjs.com/package/mongodb-memory-server)
|
337 | * [mongodb-topology-manager](https://www.npmjs.com/package/mongodb-topology-manager)
|
338 |
|
339 | ### Unofficial CLIs
|
340 |
|
341 | * [mongoosejs-cli](https://www.npmjs.com/package/mongoosejs-cli)
|
342 |
|
343 | ### Data Seeding
|
344 |
|
345 | * [dookie](https://www.npmjs.com/package/dookie)
|
346 | * [seedgoose](https://www.npmjs.com/package/seedgoose)
|
347 | * [mongoose-data-seed](https://www.npmjs.com/package/mongoose-data-seed)
|
348 |
|
349 | ### Express Session Stores
|
350 |
|
351 | * [connect-mongodb-session](https://www.npmjs.com/package/connect-mongodb-session)
|
352 | * [connect-mongo](https://www.npmjs.com/package/connect-mongo)
|
353 |
|
354 | ## License
|
355 |
|
356 | Copyright (c) 2010 LearnBoost <dev@learnboost.com>
|
357 |
|
358 | Permission is hereby granted, free of charge, to any person obtaining
|
359 | a copy of this software and associated documentation files (the
|
360 | 'Software'), to deal in the Software without restriction, including
|
361 | without limitation the rights to use, copy, modify, merge, publish,
|
362 | distribute, sublicense, and/or sell copies of the Software, and to
|
363 | permit persons to whom the Software is furnished to do so, subject to
|
364 | the following conditions:
|
365 |
|
366 | The above copyright notice and this permission notice shall be
|
367 | included in all copies or substantial portions of the Software.
|
368 |
|
369 | THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
|
370 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
371 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
372 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
373 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
374 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
375 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|