Node.js 添加数据时Mongoose架构验证不起作用

Node.js 添加数据时Mongoose架构验证不起作用,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,嘿,伙计们,我正在为我的项目使用MERN stack,我正在做的任务是使用mongoose将数据添加到我的数据库中,但首先我需要它用mongoose模式验证它,所以我所做的是 schema.js const mongoose = require("mongoose"); const Schema = mongoose.Schema; const deliverySchema = new Schema({ name: { type: String, re

嘿,伙计们,我正在为我的项目使用MERN stack,我正在做的任务是使用mongoose将数据添加到我的数据库中,但首先我需要它用mongoose模式验证它,所以我所做的是

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" });
};
控制台上的日志(数据)给了我

{
  agent_name: '',
  agent_email: '',
}
因为我发送的是空值

创建模型后,console.log(user)给了我

{ _id: 5f4cd2a2b0de8d0e7a6da675, name: '' } user
但是,为什么它会被保存在我的数据库中,因为我正在用我的猫鼬验证它,而在姓名和电子邮件字段中,我通过添加“required:true”使它们成为强制性的


如果我遗漏了什么,请原谅…

您没有使用mongoose提供的方法保存文档。您直接使用mongodb保存文档。这就是为什么文档在没有任何验证的情况下保存在数据库中

您可以使用保存文档

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);
   }
};
有关创建和保存文档的不同方法的详细信息,请参见:

在使用mongoose保存文档之前,您需要连接到数据库。有关mongoose与mongoDB的连接,请参阅:


您没有使用mongoose提供的方法保存文档。您直接使用mongodb保存文档。这就是为什么文档在没有任何验证的情况下保存在数据库中

您可以使用保存文档

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);
   }
};
有关创建和保存文档的不同方法的详细信息,请参见:

在使用mongoose保存文档之前,您需要连接到数据库。有关mongoose与mongoDB的连接,请参阅:


但我的“db”实际上就是我要添加的数据库,在这种情况下,我在哪里指定要将其添加到db?我之前做的是const db=getdb(),您需要连接到数据库,请参阅:。一旦连接,mongoose将在验证后将文档保存在数据库中。但是我的“db”实际上就是我要添加的数据库,在这种情况下,我在哪里指定要将其添加到db?我之前做的是const db=getdb(),您需要连接到数据库,请参阅:。一旦连接,mongoose将在验证后将文档保存在数据库中。