I am very confused between schema, model, instance of a model, and collection in Mongoose.
My understanding is as follows:
Is this correct?
You are mostly correct.
Firstly MongoDB is unstructured by nature, hence i recommend not trying to find "analogies" to match it to the structured scheme. With that said similarities do exist so for simplicity we can do so.
One more note is that this syntax your referring to is mongoose
specifically and not the original Mongo
syntax.
Mongoose.schema( { } )
Yes, mongoose gives you the ability to "force" a structure, note this will only come into play when trying to insert
/create
/update
documents and not when it comes to querying.
Mongoose.model('Name', Schema)
Yes-ish, mongoose will not create a database per-se, meaning if it does not exist a new one will be created, however inserting a document to that model will create a such collection.
new Model ({ //DATA })
Yes, however you need to add new Model().save()
, without the save it will not be triggered and saved into the database.
new Model ().query()
Yes-ish, again similar to the model
function this is a mongoose wrapper (that I'm less familiar with) As specified in the docs:
Query constructor used for building queries. You do not need to instantiate a Query directly. Instead use Model functions like Model.find().
Personally I just use the Model functions to query such as find
,findOne
,aggregate
and more.