【问题标题】:mongoose doesn't throw errors when an invalid data is passed to a schema将无效数据传递给模式时,猫鼬不会抛出错误
【发布时间】:2019-08-14 03:02:06
【问题描述】:

我有以下代码:

const userSchema = new mongoose.Schema({
  email: {
     type : String,
     required : true
  },
  password: String,
  username : String,
});

const User = mongoose.model('User',userSchema)


const loadCollection = async() => {
   await mongoose.connect(url,{useNewUrlParser : true})
   return mongoose.connection.collection("users");
}

现在当用户访问端点时,我需要创建一个新用户,为此我使用以下代码:

router.post('/adduser',async (req,res)=>{
    const db = await loadCollection()
    const newUser = new User({
        password : 10,
        username : 10,
    })
    try {
        await db.insertOne(newUser)
        res.status(201).send()
    } catch(e) {
        // should be triggered because of the invalid data input 
        res.status(400).send()
    }
})

如您所见,我正在将数字传递给所有这些应该是String 类型的值......我也没有传递email 这是一个必填字段......文档正在保存到数据库中没有抛出任何错误...请注意,我不想使用 save() 方法,因为我有需要使用 findOneAndUpdate 更新的子架构 有什么方法可以在不使用save() 方法以及当然使用猫鼬的情况下抛出错误。

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    您可以使用validate 方法。

    所以在你的代码中我可能会这样做:

    router.post('/adduser',async (req,res)=>{
        const db = await loadCollection()
    try {
        const newUser = new User({
            password : 10,
            username : 10,
        })
           await newUser.validate()
    
            await db.insertOne(newUser)
            res.status(201).send()
        } catch(e) {
            // should be triggered because of the invalid data input 
            res.status(400).send()
        }
    })
    

    这是mongoose 参考

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 2022-01-13
      • 1970-01-01
      • 2013-02-04
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      • 2015-11-08
      • 1970-01-01
      相关资源
      最近更新 更多