Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment.
Installation
First install node.js and mongodb. Then:
$ npm install mongoose
Connecting to MongoDB
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.
Both connect and createConnection take a mongodb:// URI, or the parameters host, database, port, options.
const 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.
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. 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.
Defining a Model
Models are defined through the Schema interface.
const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;
const 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:
- Validators (async and sync)
- Defaults
- Getters
- Setters
- Indexes
- Middleware
- Methods definition
- Statics definition
- Plugins
- pseudo-JOINs
The following example shows some of these features:
const 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.
Accessing a Model
Once we define a model through mongoose.model(‘ModelName’, mySchema), we can access it through the same function – const myModel = mongoose.model(‘ModelName’);
Or just do it all at once
const MyModel = mongoose.model(‘ModelName’, mySchema);
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
const MyModel = mongoose.model(‘Ticket’, mySchema);
Then Mongoose will create the model for your tickets collection, not your ticket collection. Once we have our model, we can then instantiate it, and save it:
const 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. 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:
const conn = mongoose.createConnection(‘your connection string’);
const MyModel = conn.model(‘ModelName’, schema);
const m = new MyModel;
m.save(); // works
vs
const conn = mongoose.createConnection(‘your connection string’);
const MyModel = mongoose.model(‘ModelName’, schema);
const m = new MyModel;
m.save(); // does not work b/c the default connection object was never connected