I am working a nodejs/express/mongoose
My model:
const TodoSchema = new mongoose.Schema({
name: { type: String, required: ['Name is required'] },
},
});
Controller :
async function createTask(req, res) {
try {
const task = new Todo({ name: req.body });
console.log(req);
console.log('Name check: ', req.name);
const result = await task.save();
console.log('check: ', task, result);
// res.send('Task created: ', result);
res.json({ msg: 'Task created', item: result });
} catch (error) {
console.log('Task creation error:', error);
return res.json({
msg: error,
});
}
}
My response in postman:
"msg": {
"errors": {
"name": {
"name": "ValidatorError",
"message": "Name is required",
"properties": {
"message": "Name is required",
"type": "required",
"path": "name"
},
"kind": "required",
"path": "name"
}
},
"_message": "Todo validation failed",
"name": "ValidationError",
"message": "Todo validation failed: name: Name is required"
}
}
and for my logs, req.name is undefined, and req.body.
I saw the docs for mongoose validation, and the type keyword, and tried the recommendations, but nothing helped. What's up with my post endpoint?
CodePudding user response:
You have an error when You use required
in Your mongoose Schema, You miss true
argument.
Here is my example =>
const mongoose = require("mongoose");
const TaskSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "You Must Provide name"],
trim: true,
maxlength: [23, "Maximum twenty characters"],
minlength: [5, "Minimum four characters"],
}
});
module.exports = mongoose.model("Task", TaskSchema);
CodePudding user response:
Maybe, you just don`t add middlewares to express.
app.use(express.json());
app.use(express.urlencoded({ extended: false }))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>