Basic Validation with Mongoose
Svep för att visa menyn
When working with data, it is important to ensure that it has the correct structure.
Mongoose allows you to define simple validation rules in your schema.
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
age: {
type: Number
}
});
Here, the name field is required. If it is missing, Mongoose will not allow the document to be saved.
app.post('/users', async (req, res) => {
try {
const user = new User(req.body);
const savedUser = await user.save();
res.json(savedUser);
} catch (error) {
res.status(400).send('validation error');
}
});
Validation helps prevent invalid or incomplete data from being stored in the database.
Var allt tydligt?
Tack för dina kommentarer!
Avsnitt 1. Kapitel 13
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal
Avsnitt 1. Kapitel 13