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);
});