【发布时间】: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() 方法以及当然使用猫鼬的情况下抛出错误。
【问题讨论】: