MongoDB - simplest Schema
-
Schema below 👇🏼 is really simplest, b/c it's more like recommendation, than require fields
See the Pen 17 - Schema (for work with MongoDb) by Andrii (@imitator) on CodePen.
Remember about reexport from folder in models/schemas/index.js
const productSchema = require('./product.schema');module.exports = {productSchema,}; -
Use Schema in Model in models/product.model.js
const { model } = require('mongoose');const { productSchema } = require('./schemas');const Product = model('product', productSchema);module.exports = Product;
Remember about reexport from models folder in models/index.js
const Product = require('./product.model');module.exports = {Product,};Collection name (in example this is model("product", ...) write as a single noun.
-
Also usually after schema added settings for mongoDb
{ versionKey: false, timestamps: true }, means don't add
version of object, but add object created time & object updated
time
See the Pen 17_A__ Schema - with settings by Andrii (@imitator) on CodePen.
-
Connection (binding) between collections has usually
making with id. So if we would like to bind product collection
with category, we add in schema field like
See the Pen 17__B__Schema_binding_collections by Andrii (@imitator) on CodePen.
So HTTP request will be with name, price & categoryID, actually we select one of the existing categories (means user selects on form).Check POST request making in this case.Look at GET Controller with populate() method.