Search code examples
databasemongoosenosqldocument-database

Mongoose commands analogous to relational database commands


I am very confused between schema, model, instance of a model, and collection in Mongoose.

My understanding is as follows:

  1. Mongoose.schema( { } ) - analogous to defining the columns of a table in relational databases
  2. Mongoose.model( 'Name', Schema) - analogous to creating a table in relational dbs (create table statement)
  3. new Model ({ //DATA }) - analogous to creating a row in relational dbs
  4. new Model ().query() - analogous to query statements (general Query) in relational dbs

Is this correct?


Solution

  • 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.

    1. 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.

    2. 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.

    3. 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.

    4. 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.