Mongoose - MongoDB Flashcards
What’s an ODM?
Object Document Mapper - It allows the ODM - which accepts the Javascript and translate it to MongoDB script and simplifies working with Database in Nodejs.
Initiate Moongoose
npm install mongoose
Connect to a Collection
mongoose.connect( ‘mongodb://localhost:27017/collection_name’ , {useNewUrlParser: true} );
Schema and Start a collection
Schema is the model on which a new collection will be based on.
const itemSchema = new mongoose.Schema( { var1: datatype here, var2: datatype here, ... });
const Item = mongoose.model( 'Item' , itemSchema ); // Anything in place of 'Item' should always be singular and collection will be saved in plural automatically.
const item1 = new Item( { var1: 2, var2: “great” …. } );
item1.save( );
Insert into the collections
//initialise the schema
const varx = new Model_name ( { var1: 3, var2: "hello" } );
const vary = new Model_name ( { var1: 3, var2: "hello" } );
Item.insertMany( [varx, vary], function (err) {
if(!err) { // log ‘great’ }
} );
Read and Find in a Collection
Model.find ( function(err, collection_name) {
if( !err )
{
console.log(collection_name);
}
});
Validation of data being input
There are built in validator in mongoose to aid in validation.
Validation like min, max for Number data type.
enum validation is used to narrow down among selected string or number.
for example in Schema initialize -
const itemSchema = new mongoose.Schema ( {
var1: {
type: Number,
min: 1,
max: 10 } ); // => This schema verifies that var1 stays in between 1 and 10 including 1 and 10.
Required Validation
the required: [ true, “comment here”] makes sure that a data field has been input by user.
Update and Delete a field in collection
Model.updateOne( {query here} , {set field here just like writing json} , function(err) { log if error or successful} );
Model.deleteOne( {query here} , function(err) { log if error or successful} );