Schema Validations



SCHEMA VALIDATION:RULES FOR SCHEMA

 const mongoose = require("mongoose");

main()
  .then(() => {
    console.log("connection successful");
  })
  .catch((err) => {
    console.log(err);
  });
async function main() {
  await mongoose.connect("mongodb://127.0.0.1:27017/amazon");
}
const bookSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
  },
  author: {
    type: String,
  },
  price: {
    type: Number,
  },
});

const Book = mongoose.model("Book", bookSchema);
let book1 = new Book({
HERE TITLE NOT DEFINED
  author: "r.r.martin",
  price: 344,
})
  .save()
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.log(err);
  });




HERE PRICE IS DEFINED AS  A STRING ,ERROR OCCURS 
IN MONGO DB VALUES ARE PARSED(CONVERTED INTO DEFINED DATATYPES)
WHEN "abc" IS PARSED IT IS NOT A NUMBER HENCE ERROR OCCURS.
const Book = mongoose.model("Book", bookSchema);
let book1 = new Book({
    title:"song of ice and fire",
  author: "r.r.martin",
  price: "abc",
})
  .save()
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.log(err);
  });


WHEN PRICE IS SENT AS A STRING LIKE"266" IT IS PARSED AND IT'S A NUMBER
const Book = mongoose.model("Book", bookSchema);
let book1 = new Book({
    title:"song of ice and fire",
  author: "r.r.martin",
  price: "266",
})
  .save()
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.log(err);
  });



Comments

Popular posts from this blog

DELETE ROUTE

CREATE ROUTE

Schema type options