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.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const childSchema = new Schema({ name: 'string' });
//1. Define a schema
const TestSchema = 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, //any type
team_id: { type: Schema.Types.ObjectId, ref: "Team" }, //allows use of populate?
array: [],
ofString: [String], // You can also have an array of each of the other types too.
nested: { stuff: { type: String, lowercase: true, trim: true } },
drink: { //enum
type: String,
enum: ['Coffee', 'Tea']
},
children: [childSchema], // Array of subdocuments
child: childSchema //Caveat: only single nested
});
});
//2. Compile model from schema
const Test = mongoose.model("Test", TestSchema);
//will use collection called Tests adding the s
module.exports = Test;
// define a schema
var animalSchema = new Schema({ name: String, type: String });
// assign a function to the "methods" object of our animalSchema
animalSchema.methods.findSimilarTypes = function(cb) {
return this.model('Animal').find({ type: this.type }, cb);
};
var Animal = mongoose.model('Animal', animalSchema);
var dog = new Animal({ type: 'dog' });
dog.findSimilarTypes(function(err, dogs) {
console.log(dogs); // woof
});
Upsert
//create if doesn't exist yet too
const user = await User.findOneAndUpdate({ email: profile.email }, payload, {
upsert: true,
new: true, //return new user not old one
setDefaultsOnInsert: true
}).exec();
To get all stories authored, have to do a find of bob._id
Story
.find({ author : bob._id })...
Can also fill in the field with the right model
const story = await Story
.findOne({ title: 'Bob goes sledding' });;
await story.populate("author").execPopulate();
story.author.name;
Callback Style
Callback Style
awesome_instance.save(function (err) {
if (err) return handleError(err);
// saved!
});
User.find({}, function(err, users) {});
// 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.
})