Mongoose
yarn add mongooseConnect mongoose as in setup
Create a model in ./models/somemodel.js
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
Model.find()//Returns[]if not foundModel.findById()//basically fineOneModel.findOne()//Returnsnullif not foundModel.findOneAndUpdate()//returns found documentsModel.updateOne()//returns object with nModified being 0
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