Security News
RubyGems.org Adds New Maintainer Role
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB.
Schema Definition
Defines a schema for a collection with various field types, validation, and defaults.
{"const mongoose = require('mongoose');\nconst Schema = mongoose.Schema;\nconst blogSchema = new Schema({\n title: String,\n author: String,\n body: String,\n comments: [{ body: String, date: Date }],\n date: { type: Date, default: Date.now },\n hidden: Boolean,\n meta: {\n votes: Number,\n favs: Number\n }\n});"}
Model Creation
Creates a model based on a defined schema, which can then be used to create, read, update, and delete documents of that schema type.
{"const mongoose = require('mongoose');\nconst Blog = mongoose.model('Blog', blogSchema);"}
Connection to MongoDB
Establishes a connection to a MongoDB database.
{"const mongoose = require('mongoose');\nmongoose.connect('mongodb://localhost/my_database', {useNewUrlParser: true, useUnifiedTopology: true});"}
Querying
Queries the database for documents matching certain criteria.
{"Blog.find({ author: 'John Doe' }).exec((err, blogs) => {\n if (err) return handleError(err);\n console.log('The blogs are', blogs);\n});"}
Data Validation
Ensures that the data being saved to the database meets certain criteria defined in the schema.
{"const personSchema = new Schema({\n name: {\n type: String,\n required: true\n },\n age: {\n type: Number,\n min: 18,\n max: 65\n }\n});"}
Middleware (Hooks)
Allows execution of code before or after certain actions, such as saving a document.
{"blogSchema.pre('save', function(next) {\n if (!this.isModified('title')) {\n return next();\n }\n this.modifiedAt = Date.now();\n next();\n});"}
Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more. Unlike Mongoose, which is designed for MongoDB, Sequelize is used for relational databases.
TypeORM is an ORM that can run in Node.js and be used with TypeScript and JavaScript (ES5, ES6, ES7, ES8). It supports both Active Record and Data Mapper patterns, unlike Mongoose which is primarily schema-based. TypeORM works with SQL databases like MySQL, PostgreSQL, and SQLite.
Waterline is a data store-agnostic ORM that is bundled in the Sails.js framework but can also be used separately. It provides a uniform API for accessing different kinds of databases, including both SQL and NoSQL, and thus offers more flexibility compared to Mongoose which is MongoDB-specific.
Bookshelf is a JavaScript ORM for Node.js, built on the Knex SQL query builder. It features both promise-based and traditional callback interfaces, transaction support, and eager/nested-eager relation loading. Bookshelf is designed for relational databases and thus is a different choice compared to Mongoose for MongoDB.
Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment.
Defining a model is as easy as:
var Comments = new Schema({
title : String
, body : String
, date : Date
});
var BlogPost = new Schema({
author : ObjectId
, title : String
, body : String
, buf : Buffer
, date : Date
, comments : [Comments]
, meta : {
votes : Number
, favs : Number
}
});
var Post = mongoose.model('BlogPost', BlogPost);
The recommended way is through the excellent NPM:
$ npm install mongoose
Otherwise, you can check it in your repository and then expose it:
$ git clone git@github.com:LearnBoost/mongoose.git support/mongoose/
// in your code
require.paths.unshift('support/mongoose/lib')
Then you can require
it:
require('mongoose')
First, we need to define a connection. If your app uses only one database, you
should use mongose.connect
. If you need to create additional connections, use
mongoose.createConnection
.
Both connect
and createConnection
take a mongodb://
URI, or the parameters
host, database, port, options
.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my_database');
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
.
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.
Models are defined through the Schema
interface.
var Schema = mongoose.Schema
, ObjectId = Schema.ObjectId;
var BlogPost = new Schema({
author : ObjectId
, title : String
, body : String
, date : Date
});
Aside from defining the structure of your documents and the types of data you're storing, a Schema handles the definition of:
The following example shows some of these features:
var Comment = new Schema({
name : { type: String, default: 'hahaha' }
, age : { type: Number, min: 18, index: true }
, bio : { type: String, match: /[a-z]/ }
, date : { type: Date, default: Date.now }
, buff : Buffer
});
// a setter
Comment.path('name').set(function (v) {
return capitalize(v);
});
// middleware
Comment.pre('save', function (next) {
notify(this.get('email'));
next();
});
Take a look at the example in examples/schema.js
for an end-to-end example of
a typical setup.
Once we define a model through mongoose.model('ModelName', mySchema)
, we can
access it through the same function
var myModel = mongoose.model('ModelName');
Or just do it all at once
var MyModel = mongoose.model('ModelName', mySchema);
We can then instantiate it, and save it:
var instance = new MyModel();
instance.my.key = 'hello';
instance.save(function (err) {
//
});
Or we can find documents from the same collection
MyModel.find({}, function (err, docs) {
// docs.forEach
});
You can also findOne
, findById
, update
, etc. For more details check out
this link.
In the first example snippet, we defined a key in the Schema that looks like:
comments: [Comments]
Where Comments
is a Schema
we created. This means that creating embedded
documents is as simple as:
// retrieve my model
var BlogPost = mongoose.model('BlogPost');
// create a blog post
var post = new BlogPost();
// create a comment
post.comments.push({ title: 'My comment' });
post.save(function (err) {
if (!err) console.log('Success!');
});
The same goes for removing them:
BlogPost.findById(myId, function (err, post) {
if (!err) {
post.comments[0].remove();
post.save(function (err) {
// do something
});
}
});
Embedded documents enjoy all the same features as your models. Defaults,
validators, middleware. Whenever an error occurs, it's bubbled to the save()
error callback, so error handling is a snap!
Mongoose interacts with your embedded documents in arrays atomically, out of the box.
Middleware is one of the most exciting features about Mongoose. Middleware takes away all the pain of nested callbacks.
Middleware are defined at the Schema level and are applied for the methods
init
(when a document is initialized with data from MongoDB), save
(when
a document or embedded document is saved).
There's two types of middleware:
.pre(method, function (next, methodArg1, methodArg2, ...) {
// ...
})
They're executed one after the other, when each middleware calls next
.
You can also intercept the method
's incoming arguments via your middleware --
notice methodArg1
, methodArg2
, etc in the pre
definition above. See
section "Intercepting and mutating method arguments" below.
.pre(method, true, function (next, done, methodArg1, methodArg2) {
// ...
})
Parallel middleware can next()
immediately, but the final argument will be
called when all the parallel middleware have called done()
.
If any middleware calls next
or done
with an Error
instance, the flow is
interrupted, and the error is passed to the function passed as an argument.
For example:
schema.pre('save', function (next) {
// something goes wrong
next(new Error('something went wrong'));
});
// later...
myModel.save(function (err) {
// err can come from a middleware
});
You can intercept method arguments via middleware.
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:
schema.pre('set', function (next, path, val, typel) {
// `this` is the current Document
this.emit('set', path, val);
// Pass control to the next pre
next();
});
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
:
.pre(method, function firstPre (next, methodArg1, methodArg2) {
// Mutate methodArg1
next("altered-" + methodArg1.toString(), methodArg2);
})
// pre declaration is chainable
.pre(method, function secondPre (next, methodArg1, methodArg2) {
console.log(methodArg1);
// => 'altered-originalValOfMethodArg1'
console.log(methodArg2);
// => 'originalValOfMethodArg2'
// Passing no arguments to `next` automatically passes along the current argument values
// i.e., the following `next()` is equivalent to `next(methodArg1, methodArg2)`
// and also equivalent to, with the example method arg
// values, `next('altered-originalValOfMethodArg1', 'originalValOfMethodArg2')`
next();
})
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:
new Schema({
broken: { type: Boolean }
, asset : {
name: String
, type: String // uh oh, it broke. asset will be interpreted as String
}
});
new Schema({
works: { type: Boolean }
, asset : {
name: String
, type: { type: String } // works. asset is an object with a type property
}
});
You can find the Dox generated API docs here.
Please subscribe to the Google Groups mailing list.
Join #mongoosejs on freenode.
The driver being used defaults to node-mongodb-native and is directly accessible through YourModel.collection
. Note: using the driver directly bypasses all Mongoose power-tools like validation, getters, setters, hooks, etc.
The following plugins are currently available for use with mongoose:
Make a fork of mongoose
, then clone it in your computer. The v2.x
branch
contains the current stable release, and the master
branch the next upcoming
major release.
Copyright (c) 2010-2011 LearnBoost <dev@learnboost.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), 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:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', 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.
FAQs
Mongoose MongoDB ODM
We found that mongoose demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.