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