0

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?

Stennie
  • 63,885
  • 14
  • 149
  • 175
lynxx
  • 544
  • 3
  • 18
  • The MongoDB manual includes a general [SQL to MongoDB Mapping Chart](https://docs.mongodb.com/manual/reference/sql-comparison/) which relates terminology, concepts, and statement between SQL and MongoDB. Mongoose adds an optional abstraction layer on top of the official [MongoDB Node.js driver](https://mongodb.github.io/node-mongodb-native/) and aims to provide a more convenient interface for developers. – Stennie Jan 18 '20 at 23:31

1 Answers1

1

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.

Tom Slabbaert
  • 21,288
  • 10
  • 30
  • 43