Node.js 猫鼬不';当向架构传递无效数据时,不会抛出错误

Node.js 猫鼬不';当向架构传递无效数据时,不会抛出错误,node.js,mongoose,Node.js,Mongoose,我有以下代码: constuserschema=newmongoose.Schema({ 电邮:{ 类型:字符串, 必填项:true }, 密码:String, 用户名:String, }); const User=mongoose.model('User',userSchema) const loadCollection=async()=>{ wait mongoose.connect(url,{useNewUrlParser:true}) 返回mongoose.connection.coll

我有以下代码:

constuserschema=newmongoose.Schema({
电邮:{
类型:字符串,
必填项:true
},
密码:String,
用户名:String,
});
const User=mongoose.model('User',userSchema)
const loadCollection=async()=>{
wait mongoose.connect(url,{useNewUrlParser:true})
返回mongoose.connection.collection(“用户”);
}
现在,当用户访问端点时,我需要创建一个新用户,为此,我使用以下代码:

router.post('/adduser',异步(req,res)=>{
const db=await loadCollection()
const newUser=新用户({
密码:10,
用户名:10,
})
试一试{
等待数据库插入器(新用户)
res.status(201).send()
}捕获(e){
//由于数据输入无效,应触发
res.status(400).send()
}
})
如您所见,我正在将数字传递到所有这些值中,这些值的类型应为
String
。。。另外,我没有传递
电子邮件
,这是必填字段。。。正在将文档保存到数据库中,而不会引发任何错误。。。请注意,我不想使用
save()
方法,因为我有需要使用
findOneAndUpdate

是否有任何方法可以在不使用
save()
方法的情况下抛出错误,当然也可以使用mongoose。

您可以使用
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()
    }
})

这是参考

您可以使用
验证
方法

因此,在您的代码中,我可能会这样做:

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()
    }
})
这是参考资料