Mongoose Primer
Installing Mongoose and MongoDB
- First step is install Mongoose and MongoDB
- To install mongoose – npm install mongoose.
- For Mongo, we can either have a local installation, or cloud based database service.
- Local installation instructions here: download installers from here
- MongoDB Atlas here: MongoDB Atlas
- Part one is connecting to MongoDB.
- We need to require this.
Connecting to a MongoDB
- This is the code to connect to a locally hosted database:
//Import the mongoose module
var mongoose = require('mongoose');
//Set up default mongoose connection
var mongoDB = 'mongodb://127.0.0.1/my_database';
mongoose.connect(mongoDB, {useNewUrlParser: true, useUnifiedTopology: true});
//Get the default connection
var db = mongoose.connection;
//Bind connection to error event (to get notification of connection errors)
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
- Default connection object – mongoose.connection
- Once connected, the event is fired on the connection instance.
- Can also create additional connections – mongoose.createConnection()
Defining and creating models
- Models are defined in the Schema interface.
- Allows us to define fields and their validation requirements/ default values.
- Can also define static and instance helper methods – make it easier to work with the data types.
- Also virtual properties.
- Schemas are then compiled into models (using mongoose.model())
- Models can be used to find objects to CRUD
- Each model – maps to a collections of documents in the MongoDB database.
Defining schemas
- This is how you might define schemas:
//Require Mongoose
var mongoose = require('mongoose');
//Define a schema
var Schema = mongoose.Schema;
var SomeModelSchema = new Schema({
a_string: String,
a_date: Date
});
- Two fields, a string and a date.
Creating a model
- Models are created from schemas using mongoose.model() method.
// Define schema
var Schema = mongoose.Schema;
var SomeModelSchema = new Schema({
a_string: String,
a_date: Date
});
// Compile model from schema
var SomeModel = mongoose.model('SomeModel', SomeModelSchema );
- First argument – singular name of the collection that will be created for your model
- Second argument – schema you want to use in creating the model.
Schema types (fields)
- A schema can have an arbitrary number of fields.
- Each one represents a field in the documents stored in MongoDB
var schema = new Schema(
{
name: String,
binary: Buffer,
living: Boolean,
updated: { type: Date, default: Date.now() },
age: { type: Number, min: 18, max: 65, required: true },
mixed: Schema.Types.Mixed,
_someId: Schema.Types.ObjectId,
array: [],
ofString: [String], // You can also have an array of each of the other types too.
nested: { stuff: { type: String, lowercase: true, trim: true } }
})
Validation
- Mongoose provides built in and custom validators
var breakfastSchema = new Schema({
eggs: {
type: Number,
min: [6, 'Too few eggs'],
max: 12,
required: [true, 'Why no eggs?']
},
drink: {
type: String,
enum: ['Coffee', 'Tea', 'Water',]
}
});
Virtual Properties
- document properties that you can get and set but that do not get persisted to MongoDB
Using models
- Once you’ve created a schema. you can use it to create models.
- Model represents a collection of documents in the database that you can search.
- Models instances – represent individual documents you can save and retrieve.
Creating and modifying documents
- Create a record – define an instance of the model, the call save.
// Create an instance of model SomeModel
var awesome_instance = new SomeModel({ name: 'awesome' });
// Save the new model instance, passing a callback
awesome_instance.save(function (err) {
if (err) return handleError(err);
// saved!
});
- Asynchronous operation s – callbacks need to be provided.
- Every model has an associated connection.
- Create new connection and call. model() on it to create the documents on a different database.
- Access and change the values using dot syntax.
- Then have to call save or update.
// Access model field values using dot notation
console.log(awesome_instance.name); //should log 'also_awesome'
// Change record by modifying the fields, then calling save().
awesome_instance.name="New cool name";
awesome_instance.save(function (err) {
if (err) return handleError(err); // saved!
});
Searching for records
- Search for records using query methods, specifying the query conditions as a JSON document.
- For example:
var Athlete = mongoose.model('Athlete', yourSchema);
// find all athletes who play tennis, selecting the 'name' and 'age' fields
Athlete.find({ 'sport': 'Tennis' }, 'name age', function (err, athletes) {
if (err) return handleError(err);
// 'athletes' contains the list of athletes that match the criteria.
})
- Can also build up your query by not specifying the callback:
// find all athletes that play tennis
var query = Athlete.find({ 'sport': 'Tennis' });
// selecting the 'name' and 'age' fields
query.select('name age');
// limit our results to 5 items
query.limit(5);
// sort by age
query.sort({ age: -1 });
// execute the query at a later time
query.exec(function (err, athletes) {
if (err) return handleError(err);
// athletes contains an ordered list of 5 athletes who play Tennis
})
- Or:
Athlete.
find().
where('sport').equals('Tennis').
where('age').gt(17).lt(50). //Additional where query
limit(5).
sort({ age: -1 }).
select('name age').
exec(callback); // where callback is the name of our callback function.
Working with related documents – population
- Can create references from one document to another – using the ObjectId schema field.
- Can use populate() to get the actual content.
- For example, the following schema defines authors and stores.
- Each author can have multiple stories (array of ObjectId)
- Each story can have a single author.
- Ref – tells the schema which model can be assigned to this field
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var authorSchema = Schema({
name : String,
stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
var storySchema = Schema({
author : { type: Schema.Types.ObjectId, ref: 'Author' },
title : String
});