gpt4 book ai didi

node.js - 当无效数据传递给模式时,mongoose 不会抛出错误

转载 作者:行者123 更新时间:2023-12-05 07:20:30 26 4
gpt4 key购买 nike

我有以下代码:

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() 的情况下抛出错误?方法,当然还有 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()
}
})

这是 mongoose引用

关于node.js - 当无效数据传递给模式时,mongoose 不会抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57480627/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com