RRR uzumaki
RRR uzumaki

Reputation: 1328

Mongoose schema validation not working while adding data

Hey guys i am usin MERN stack for my project, the task i am doing is to add data to my db with mongoose but first i need it to validate it with mongoose schema so what i did was

schema.js

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const deliverySchema = new Schema({
  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },

});

const Agent= mongoose.model("delivery_agent", deliverySchema);
module.exports=Agent

controller.js

 const Agent=require("../../../models/deliveryAgent")
 exports.addDeliveryAgent = async (req, res, next) => {
  let data=req.body.data
  console.log(data)
  const db = getdb();
  const user = new Agent({
    name: data.agent_name,
  });

  console.log(user, "user");
  db.collection("delivery_agent")
    .insertOne({ user })
    .then((result) => {
      console.log("Delivery agent saved !");
    })
    .catch((err) => {
      console.log(err);
    });
  res.json({ status: 200, message: "Delivery Agent added" });
};

console.log(data) on consoling gives me

{
  agent_name: '',
  agent_email: '',
}

as i am sending empty values

console.log(user) after creating a model gives me

{ _id: 5f4cd2a2b0de8d0e7a6da675, name: '' } user

but then why is it getting saved in my db as i am validating it with my mongoose and there for name and email fields i have made them compulsary by adding "required:true".

Pardon me if i miss something here ...

Upvotes: 1

Views: 2345

Answers (1)

Yousaf
Yousaf

Reputation: 29282

You are not using the methods provided by mongoose to save the document. You are using mongodb directly to save the document. That is why, document gets saved in the database without any validation.

You can use Model.prototype.save() to save the document.

const Agent = require("../../../models/deliveryAgent");

exports.addDeliveryAgent = async (req, res, next) => {
   let data = req.body.data;
   
   try {
      const user = new Agent({
         name: data.agent_name,
      });

      await user.save();
      res.json({ status: 200, message: "Delivery Agent added" });

   } catch(error) {
      console.log(error);
   }
};

For details of different ways of creating and saving documents, see:

You will need to connect to the database before saving the document using mongoose. For connecting mongoose with the mongoDB, see:

Upvotes: 2

Related Questions