【问题标题】:Mongoose schema validation not working while adding data添加数据时猫鼬模式验证不起作用
【发布时间】:2020-12-19 11:29:08
【问题描述】:

大家好,我正在为我的项目使用 MERN 堆栈,我正在做的任务是使用 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" });
};

console.log(data) 上的安慰给了我

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

因为我发送的是空值

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

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

但是为什么它被保存在我的数据库中,因为我正在用我的猫鼬验证它,并且在那里我通过添加“required:true”使它们成为强制性的。

如果我在这里遗漏了什么,请原谅我......

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    您没有使用猫鼬提供的方法来保存文档。您正在使用 mongodb 直接保存文档。这就是为什么文档未经任何验证就保存在数据库中的原因。

    您可以使用Model.prototype.save() 来保存文档。

    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 - Connections。连接成功后,mongoose 会将文档保存在数据库中。
    猜你喜欢
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2018-11-16
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多