每当我尝试将模式保存到数据库时,它仅保存id,而不保存我想要保存的实际数据。我通过调试对其进行了检查,然后再看到一个问题,即req.body中不包含任何查询。如何解决这个问题
const userSchema = new mongoose.Schema({
name: {
type: String
},
age: {
type: Number,
required: false,
validate(value) {
if (value < 18) {
throw new Error("age Must be greater than 18")
}
}
},
password: {
type:String,
minlength: 7,
validate(value) {
if (value === 'password') {
throw new Error("Password can not be named password")
//console.log(`password can't be password`)
}
}
},
email: {
type: String,
validate(value) {
if (!validator.isEmail(value)) {
return console.log('invalid Email!')
}
}
}
})
userSchema.statics.findByValues = async (email, password) => {
const user = await User.findOne({ email });
if (!user) {
throw new Error("unable to login");
}
const isMatch = await bcrypt.compare(password, user.password)
if (!isMatch) {
throw new Error("unable to login");
}
}
userSchema.pre('save', async function (next) {
const user = this
if (user.isModified('password')) {
user.password = await bcrypt.hash(user.password, 8)
}
next();
})
const User = mongoose.model('User', userSchema)
router.post('/user', async (req, res)=>{
const user = new User(req.body);
try{`enter code here`
await user.save();
res.send(user);
console.log(req.body)
} catch(e){
res.status(404).send(e);
}
})
这是用户架构模型