w6- advanced mongodb Flashcards
How to have strongly-typed documents?
MongooseJS
MongooseJS
strongly-typed schemas, data validation, data pre-processing, and many other features.
one-to-one rel approaches?
author_id as property of book.
let Author = {
_id: 1234,
firstName: ‘Tim’,
lastName: ‘John’,
age: 35
};
let book1 = {
_id: 789,
title: ‘FIT2095 Book’,
author_id: 1234,
isbn: 9876
}
Mongoose
object data modelling (ODM) library that provides a modelling environment for your collections.
enforces structure as needed while still keeping the flexibility and scalability of MongoDB.
JavaScript framework commonly used in a Node.js application with a MongoDB database
built-in typecasting, validation, query building, business logic hooks and more out of the box.
How does Mongoose interact with MongoDB?
It uses the MongoDB driver to interact with MongoDB storage.
.
Mongoose SchemaTypes?
currently contains eight SchemaTypes that a property is saved as when it is persisted to MongoDB.
String
Number
Date
Buffer
Boolean
Mixed
ObjectId
Array
Decimal128
Map
SchemaTypes handle the definition of?
defaults
validation
getters
setters
field selection defaults for queries
Schema?
Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.
Field is mandatory?
required:true
make a field required, set the field an object with two properties: the type and required, which needs a boolean value.
age: {
type: Number,
validate: {
validator: function (ageValue) {
return ageValue >= 10 && ageValue <= 110;
},
message: ‘Age should be a number between 10 and 110’
}
}
Validator if it is between 10 and 110
age: { type: Number, min: 5, max: 20 }
Anbother way to validator Mongoose
created: {
type: Date,
default: Date.now
}
field has default date
Boook schema referencing author
author: {
type: mongoose.Schema.Types.ObjectId,
ref: ‘Author’
},
Mongoose models?
Models are higher-order constructors that take a schema and create an instance of a document equivalent to records in a relational database
A Mongoose model is a wrapper on the Mongoose schema.
Difference b/w mongoose schema and mongoose model?
Mongoose schema defines the structure of the document, default values, validators, etc.,
whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.
module.exports = mongoose.model(‘Author’, authorSchema);
to export a model, we need to invoke the model constructor and pass it a string represents the name of the collection and a reference to the schema.
author collection
let url=’mongodb://localhost:27017/libDB’;
Mongoose URL string which has syntax: mongodb://ServerAddress: Port//DbName
format
adding new book
saving book
Note: the creating and saving of book1 and book2 have been implemented inside the callback of author1.save function. Why?? N
Node.js is asynchronous and both book1 and book2 require the author’s ID (lines 31 and 43). Therefore, we have to create them after the save operation of the author is done.
.insertMany() function
This function takes as input an array of documents (objects) and inserts them if they are valid.
Mongoose models have several static functions that can be used for CRUD operations?
Model.deleteMany()
Model.deleteOne()
Model.find()
Model.findById()
Model.findByIdAndDelete()
Model.findByIdAndRemove()
Model.findByIdAndUpdate()
Model.findOne()
Model.findOneAndDelete()
Model.findOneAndRemove()
Model.findOneAndUpdate()
Model.replaceOne()
Model.updateMany()
Model.updateOne()
Using ‘where’, we can create complex expressions. Example: Find all documents with firstName starting with the letter ‘T’ and the age >= 25.
Author.where({ ‘name.firstName’: /^T/ }).where(‘age’).gte(25).exec(function (err, docs) {
console.log(docs);
});
What does exec mean?
Note exec indicates the end of the chain and invokes the callback function.
and sort the results in ascending order by the age
Author.where({ ‘name.firstName’: /^T/ }).where(‘age’).gte(25).lte(35).limit(10).sort(‘age’).exec(function (err, docs) {
console.log(docs);
});
Author.find({ ‘name.firstName’: ‘Tim’ }, ‘age’, function (err, docs) {
//docs is an array
console.log(docs);
});
Retrieving only certain fields Example: get the age of all documents with first name = ‘Tim’
Populate?
Mongoose has a powerful aggregation operator called populate(), which allows you reference documents in other collections.
Book.find({}).populate(‘author’).exec(function (err, data) {
console.log(data);
});
For exmaple, to get the books and their authors’ details:
Author.updateOne({ ‘name.firstName’: ‘Alex’ }, { $set: { ‘name.firstName’: ‘John’ } }, function (err, doc) {
console.log(doc);
});
This document updates only the first document that matches the criteria.
Author.deleteOne({ ‘name.firstName’: ‘Tim’ }, function (err, doc) {
console.log(doc);
});
Author.deleteMany({ ‘name.firstName’: ‘Tim’ }, function (err, doc) {
console.log(doc);
});
deleteOne() function deletes a document based on condition (criteria).
This function deletes all the documents that match the criteria.
Deployment workflow this unit- 3 stages
1.testing functionality in local machine
2.pushed to a VCS repository i.e Github - intermediary between IDE and GCP VM instances i.e production
clon source code to VM instane- fetch dependencies- build and execute app
IDE ->push->Github->clone-> GCP VM-> production!
Cloud computing models!
3 cloud computing models- IaaS
PaaS
SaaS
IaaS
Infrastructure as a Service- IaaS is a form of cloud computing that offers virtualized resources over the internet. In this form, you can create your network of resources: Virtual Machines (VMs), firewalls, and load balancers
PaaS
Platform as a Service-PaaS is a form of cloud computing where the infrastructure will be created and managed by the cloud vendor, and your responsibility as a developer is to provide the application’s source code.
SaaS
Software as a Service- The cloud vendor will manage the infrastructure and application source code in this form.
Bootstrap
Bootstrap is the most popular CSS Framework for developing responsive and mobile-first websites.
Is integer?
var itemSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
itemName: String,
quantity: {
type: Number,
validate: {
validator: Number.isInteger,
message: ‘The quantity is not an integer value’
}
}
});
Retrieve the first 50 documents with quantity between 100 and 150 inclusive.
Items.where(‘quantity’).gte(100).lte(150).limit(50).exec(function (err, docs) {
// Do something with Docs
});
const mongoose = require(“mongoose”);
let doctorSchema = mongoose.Schema({
_id: {
type: mongoose.Schema.Types.ObjectId,
auto: true
},
name: {
firstName: {
type: String,
required: true,
},
lastName: String,
}
});
Add a validator to the schema, so it only accepts documents with at least 5 characters in firstName. The message for invalid data is ‘firstName length cannot be less than 5’.
const mongoose = require(“mongoose”);
let doctorSchema = mongoose.Schema({
_id: {
type: mongoose.Schema.Types.ObjectId,
auto: true
},
name: {
firstName: {
type: String,
required: true,
validate:{
validator: function (firstNameValue){
return firstName.length >= 5;
},
message = ‘‘firstName length cannot be less than 5’.
}
},
lastName: String,
}
});
What are the roles on param in the following statement:
module.exports = mongoose.model(param, mySchema);
param - unique name i.e String to reference collection , collection name in database.
How does populate work in mongoose? Support with example
Mongoose has a powerful aggregation operator called populate(), which allows you reference documents in other collections.
For exmaple, to get the books and their authors’ details:
Book.find({}).populate(‘author’).exec(function (err, data) {
console.log(data);
});