Chengyu Sun California State University, Los Angeles CS5220 Advanced Topics in Web Programming Object-Document Mapping with Mongoose Chengyu Sun California State University, Los Angeles
Why Mongoose? Document != Object ObjectID is not object reference No methods Simplify data access and validation (similar validation capabilities were added to MongoDB in 3.6)
Basic Usage of Mongoose Example: test4.js mongoose package Schema and model Connect and disconnect Basic operations Callback and Promise
Schema and Model Mongoose Java Schema Data Model Class Model DAO Fields Methods Data Model Class Fields Methods Constructors Model Constructors Data access methods DAO Data access methods
Schema Example const mongoose=require('mongoose'); let userSchema = mongoose.Schema({ name: String, email: String }); Map to a collection in MongoDB Defines the structure of the documents in the collection: properties, methods, constraints, and indexes A _id field of ObjectId is created by default
Schema Types String Number Boolean Date Buffer ObjectId Decimal128 Schema.Types.ObjectId Decimal128 Schema.Types.Decimal128 Mixed Schema.Types.Mixed Array []
Schema Type Example Schema Schema new Schema({ title: String, text: String, date: Date, authorId: Schema.Types.ObjectId, tags: [String], comments: [{ author: { id: Schema.Types.ObjectId, name: String }, date: Date }] }); Schema Schema
Additional Property Options For all properties: required, default, validate … Type-specific: lowercase, uppercase, trim, min, max … Index-related: index, unique, sparse
Property Option Example new Schema({ username: { type: String, required: true, unique: true, lowercase: true, trim: true, validate: function(value){ return value.length > 6; } });
Add Methods to Schema userSchema.methods.name = function(){ return this.firstName + ' ' + this.lastName; } userSchema.statics.findByEmail = function(email, callback) { return this.find({email:email}, callback);
Model Models are constructors created from schema definitions Models can be used to create objects that are mapped to documents in database Models have built-in methods that access database and convert between objects and documents (like DAO in ORM)
Create Models User = mongoose.model('User', userSchema); or name: String, email: String });
Create Models Create a model with the given schema User = mongoose.model('User', userSchema); or User = mongoose.model('User', { name: String, email: String }); Create a model with the given schema Register the model with Mongoose under the given name (so it can be retrieved later) Return the model
CRUD with Model Example: blogs-test.js Use of Model methods and Model prototype methods Callback and Promise Model.find() returns a Query Query can be used a Promise (i.e. has a then() method) Query building
Ref and Populate Comparison to Jackson?? articleSchema = Schema({ author: { type: Schema.Types.ObjectId, ref: 'User' } }); articles = Article.find().populate('author'); Comparison to Jackson??
Inheritance userSchema = new Schema({name: String}); User = mongoose.model('User', userSchema); Student = User.discriminator('Student', new Schema({cin, String}) ); Model.discriminator() creates a new model with the given name by combining the given schema with the model's schema
About Inheritance Example: inheritance-test.js The documents of both models will be stored in the same collection The default discriminator field is __t Model.find() is not polymorphic though
Readings Mongoose Documentation