Mongoose: Schema vs Model?
Asked Answered
R

5

64

When looking at tutorials there is often a delineation between a schema and a model, particularly when dealing with mongoose/mongodb. This makes porting over to postgresql somewhat confusing, as 'models' don't seem to exist under that system. What is the difference the two approaches?

For example, what would be a postgres/sql ORM equivalent of this line?

(mongoose and express.js):

var userSchema = schema.define('local', {
    username:       String,
    password:       String,
});

module.exports = mongoose.model('User', userSchema);
Recipe answered 8/4, 2014 at 23:42 Comment(2)
possible duplicate of Why does Mongoose have both schemas and models?Unfrock
@Unfrock I did give this a read through, but my question is more geared towards the equivalent postgresql workflow (rather than a discussion purely within the realm of Mongoose)Recipe
A
124

In mongoose, a schema represents the structure of a particular document, either completely or just a portion of the document. It's a way to express expected properties and values as well as constraints and indexes. A model defines a programming interface for interacting with the database (read, insert, update, etc). So a schema answers "what will the data in this collection look like?" and a model provides functionality like "Are there any records matching this query?" or "Add a new document to the collection".

In straight RDBMS, the schema is implemented by DDL statements (create table, alter table, etc), whereas there's no direct concept of a model, just SQL statements that can do highly flexible queries (select statements) as well as basic insert, update, delete operations.

Another way to think of it is the nature of SQL allows you to define a "model" for each query by selecting only particular fields as well as joining records from related tables together.

In other ORM systems like Ruby on Rails, the schema is defined via ActiveRecord mechanisms and the model is the extra methods your Model subclass adds that define additional business logic.

Aeromechanics answered 8/4, 2014 at 23:53 Comment(2)
Thanks for the answer. I see in some places a User object is still created like this and called a 'model' even using postgres: "var User = sequelize.define('user', { field:value});" which is passed into the main app. Is this simply a schema definition? Source is sarabinns.com/tag/passport-js-sequelize-postgresqlRecipe
The {field:value) part is the schema. The User part is the model.Aeromechanics
V
9

A schema is fundamentally describing the data construct of a document (in MongoDB collection). This schema defines the name of each item of data, and the type of data, whether it is a string, number, date, Boolean, and so on.

A model is a compiled version of the schema. One instance of the model will map to one document in the database. It is the model that handles the reading, creating, updating, and deleting of documents. A document in a Mongoose collection is a single instance of a model. So it makes sense that if we're going to work with our data then it will be through the model. A single instance of a model (like a User instance in var User = mongoose.model('User', userSchema);) maps directly to a single document in the database. With this 1:1 relationship, it is the model that handles all document interaction - creating, reading, saving, and deleting. This makes the model a very powerful tool.

Taken from "Mongoose for Application Development", by Simon Holmes, 2013

I imagine models as classes created from a schema (maybe I am mistaken).

MongoDB stores everything in BSON , which is a binary format. A simple Hello World BSON document might look like this internally: \x16\x00\x00\x00\x02hello\x00\x06\x00\x00\x00world\x00\x00. A computer can deal with all that mumbo-jumbo, but that's hard to read for humans. We want something we can easily understand, which is why developers have created the concept of a database model. A model is a representation of a database record as a nice object in your programming language of choice. In this case, our models will be JavaScript objects. Models can serve as simple objects that store database values, but they often have things like data validation, extra methods, and more. As you’ll see, Mongoose has a lot of those features.

Taken from "Express in Action", by Evan Hahn, 2016

Virology answered 27/8, 2021 at 9:24 Comment(0)
U
1

In Short:

A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.

Reference: Introduction to Mongoose for MongoDB - FCC

Uniat answered 30/7, 2021 at 8:27 Comment(0)
P
1

Simple answer!
Schema
Schema is the representation of data, which means how data will look like
Modal
Modal is Api that you use to interact with the database

Prokopyevsk answered 8/2 at 10:22 Comment(0)
C
0

In Mongoose, a schema defines the structure of a document or record in a MongoDB collection. It defines the fields, their types, their default values, and any validation rules that should be applied to the data.

A model, on the other hand, is a class that represents a MongoDB collection. It is created by compiling a schema. It allows you to interact with a MongoDB collection in a more intuitive way by providing an interface for querying, inserting, updating, and deleting documents in the collection.

In short, A schema is compiled into a model, which can then be used to create, read, update, and delete documents in a MongoDB collection.

Note:

Multiple models can be created from a single schema, each representing a different MongoDB collection.

Schema is defined once and used repeatedly, while a model can be instantiated multiple times to work with different documents in the collection.

Check this code:

import mongoose from "mongoose";

// Define a schema for a user document
const userSchema = new mongoose.Schema({
  firstName: {
    type: String,
    required: true
  },
  lastName: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true,
    unique: true
  },
  age: {
    type: Number,
    required: false,
    default: null,
    min: 18
  }
});

// Create a model for the user collection based on the user schema
const User = mongoose.model('User', userSchema);

// Use the User model to create and save a new user document
const newUser = new User({
  firstName: 'John',
  lastName: 'Doe',
  email: '[email protected]',
  age: 25
});

newUser.save()
  .then(doc => console.log(doc))
  .catch(err => console.error(err));
Closefisted answered 15/3, 2023 at 12:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.