constmongoose=require('mongoose');constmongoDB='mongodb://127.0.0.1/my_database';mongoose.connect(mongoDB);//usually mongoose uses pseudo promises, this tells it to use real onesmongoose.Promise =global.Promise;//Get the default connectionconstdb=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.
constmongoose=require('mongoose');constSchema=mongoose.Schema;constchildSchema=newSchema({ name:'string' });//1. Define a schemaconstTestSchema=newSchema({ 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 schemaconstTest=mongoose.model("Test", TestSchema);//will use collection called Tests adding the smodule.exports= Test;
// define a schemavar animalSchema =newSchema({ name: String, type: String });// assign a function to the "methods" object of our animalSchemaanimalSchema.methods.findSimilarTypes=function(cb) {returnthis.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 tooconstuser=awaitUser.findOneAndUpdate({ email:profile.email }, payload, { upsert:true, new:true,//return new user not old one setDefaultsOnInsert:true}).exec();
awesome_instance.save(function (err) {if (err) returnhandleError(err);// saved!});User.find({},function(err, users) {});// find all athletes who play tennis, selecting the 'name' and 'age' fieldsAthlete.find({ 'sport':'Tennis' },'name age',function (err, athletes) {if (err) returnhandleError(err);// 'athletes' contains the list of athletes that match the criteria.})