Mongoose

yarn add mongoose
  1. Connect mongoose as in setup

  2. Create a model in ./models/somemodel.js

  3. Import model in routes and use model fts

Setup

const mongoose = require('mongoose');

const mongoDB = 'mongodb://127.0.0.1/my_database';
mongoose.connect(mongoDB);
//usually mongoose uses pseudo promises, this tells it to use real ones
mongoose.Promise = global.Promise;

//Get the default connection
const db = mongoose.connection;
//Bind connection to error event (to get notification of connection errors)
db.on('error', console.error.bind(console, 'MongoDB connection error:'));

Defining Models

Models are defined using the Schema interface.

Schema Types

  • Can also have instance methods, static methods, and speciality queries

    Virtual

Fields that dont exist in db

Can now do Author.name

Using Models

Creating

Use mongoose.Types.ObjectId(uid) to convert string to objectID

Querying

Use .exec() to give you a promise, make sure to have set mongoose.Promise in setup

Count

returns number >= 0

Advanced

Model Instance Methods

Upsert

References

To get all stories authored, have to do a find of bob._id

Can also fill in the field with the right model

Callback Style

Callback Style

Last updated