INTRO CHEATSHEETTO DATABAS ES

[Pages:3]INTROTODATABASES

CHEATSHEET

ConnectingtoMongoDBandusingMongoose,aNodeJSlibrarythatallowsMongoDBintegration

MongoDBTerminology

Database Adatabaseisusedtostoreallcollections. Collection Storesanumberofdocuments.Acollectionshouldstore documentsofthesametype,althoughthisconstraintis notexplicitlyenforcedbyMongoDB. Document Eachrecordinacollectionisadocument.Documentsare composedofkey/valuepairs. ObjectId TheObjectIdclassisthedefaultprimarykeyfora MongoDBdocumentandisusuallyfoundinthe_idfi eld inaninserteddocument.Alldocumentsare automaticallyassignedauniqueidwhenaddedtoa collection.

SchemaTypes

String ?Text

Number ?Aninteger

Date ?Asinglemomentintime

Buffer ?Binarydata

Boolean ?Oneof{true,false}

Mixed ?"Anythinggoes".Ifsettomixed,anyother

typewillbeaccepted

ObjectId ?AuniqueID,typicallyusedtoidentify

documents

Array ?Alistofvalues

constsomeSchema=newSchema({ names:[String], items:Array, });

Youcanandshouldspecifythetypeoftheelementsinside anarray,asinthisexample.Nameshasaspecifiedtypeof elementsinthearraywhileitemsdoesnot.

MongooseTerminology

Schema Adescriptionofthedatastructure.ASchemadefi nesthe fi eldnamesandtheircorrespondingtime,whichhelps withvalidation,defaults,andotheroptionsinour models. Model Amodelistheprimarytoolforinteractingwith MongoDB.Itisafancyconstructorforadocument. Modelsareresponsibleforcreatingandreading documentsfromtheunderlyingMongoDBdatabase. Validation Bydefault,MongoDbdoesnotrequirethedocumentsin acollectiontohavethesameschema.Inotherwords,the documentsdonothavetohavethesamefi eldsanddata types.Validationallowsyoutodefi nethestructureofthe documentsinacollection. Ifadocumentdoesnotfi ttheschema,theinsertionwill berejected.

MongooseInstallation

AddtheMongoosepackagetoyourproject

$npminstall--savemongoose

ImportMongoose

TheMongoosepackageneedstobeincludedinevery JSfileitisusedin.

constmongoose=require("mongoose"); Importsthepackageandsavestotheconstantmongoose

SettingUpAtlas

AtlasisanonlineservicethathostsMongodatabases. Signupatcloud/atlas.Createa cluster,auserwithatleastreadwritepermissions,and connecttoyourproject.

INTROTODATABASES

CHEATSHEET

ConnectingtoMongoDBandusingMongoose,aNodeJSlibrarythatallowsMongoDBintegration

ConnecttoMongoDB

UseyourSRVfromourMongoDBprovider,Atlas,to connectwithMongoose.

constmongoConnectionURL="mongodb+srv:// USERNAME:PASSWORD@DB.test? retryWrites=true"; constdatabaseName="someDatabaseName"; constoptions={ useNewUrlParser:true, useUnifiedTopology:true, dbName:databaseName, }; mongoose.connect(mongoConnectionURL,options) .then(()=>console.log("Connected.")) .catch((error)=>console.log(`Error connectingtoMongoDB${error}`));

HeremongoURLissettotheSRVgivenforaclusteronAtlas

CreatingaSchema

constStudentSchema=newmongoose.Schema({ name:String, age:Number, classes:[String], });

Herewehavecreatedaschemawithattributesname,age, andclass.Nameisastring.Ageisanumber.Andclassesare anarrayofthespecifictype,String.

CreatingaModel

AmodeliscompiledfromaSchema.

module.exports=mongoose.model("ModelName", StudentSchema);

Herewecreatedamodelbasedontheschemawedefined above.Rememberthatthefirstargumentspecifiesthename ofthecollection.

FindingaDocument

Wewillbeusingqueriestofinddocumentsinacollection.

DefiningaQuery

Aquerydescribeshowtofilterdocumentstospecify whichdocumentstoreturn.

constemptyQuery={}; Anemptyquery,asabove,returnsalldocuments.

constquery={name:"Tim",age:21}; ThisquerywouldreturnalldocumentswiththenameTim andtheage21.

FindingwithaQuery

Belowaretwowaystofindusingaquery.

Student.find(query) .then((students)=> console.log(`found${students.length}`)); FindreturnsaPromisewithalldocumentsthatmatchthe query.Here,ouranonymousfunctiontakesthereturned documentsandlogssomeinformation.

Student.findOne(query) .then((student)=> console.log(`found${student.name}`)); Findonereturnsonlyonedocumentthatmatchesthequery.

INTROTODATABASES

CHEATSHEET

ConnectingtoMongoDBandusingMongoose,aNodeJSlibrarythatallowsMongoDBintegration

FindingDocumentswithaCertain Key-ValuePair

Belowaretwowaystofindadocumentwithacertain key-valuepair.

Student.find({key:someValue}) .then((student)=>console.log("Found"));

Student.find({}) .where(key).equals(someValue) .then((student)=>console.log("Found"));

DeletingaDocument

Student.deleteOne(query) .then((student)=>console.log("Deleted"));

Thisonlydeletesonedocumentthatmatchesthequery.

Student.deleteMany(query) .then((student)=> console.log("Deletedmanydocuments"));

Thisonlydeletesonedocumentthatmatchesthequery.

InsertingaDocument

conststudent=newStudent({ name:"myname", age:20, classes:["weblab"], }) student.save() .then((student)=>console.log("Inserted"));

WecreateanewStudentdocumentandthensaveittoinsert thedocument.

CommonMongoErrors

Makesureyou'veinstalledandimportedMongoose. IfconnectionissuestoAtlas,try: *checkingthevalidityofyourAtlasSRV *restartingyourserverandtryagain

UpdatingaDocument

Student.findOne(query) .then((student)=>{ student.fieldToUpdate=newValue; student.save() });

Weusefindonetoensurethatweonlyupdateone document.

HelpfulResources



................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download