Express-validator throwing error with valid fields - javascript

I'm relatively new to node and express, and have come across a problem I can't seem to solve.
So I came across with the problem trying to validate a create product form, that when I introduce correct values into the fields express-validator throws error.
This is my routes code:
router.post('/create', [
check('name').isLength({ min: 5 }).withMessage("Invalid Value"),
check('description').isLength({ min: 20 }).withMessage("Invalid Value")
] , upload.any() , productosController.guardarCreado);
This is my productosController code:
guardarCreado: (req, res, next) => {
let errors = validationResult(req);
if(errors.isEmpty()){
db.Product.create({
name: req.body.nombre,
description: req.body.descripcion,
size: req.body.talle,
price: req.body.precio,
category_id: 2,
img_url: req.files[0].filename
})
res.redirect('/productos');
}else{
db.Category.findAll()
.then(function(categorias){
return res.render('crearProductos', { categorias: categorias, errors: errors.errors });
})
}
}
And my form code is from Bootstrap and the names of the form fields are the same as the names on the 'check' from my routes code:
<div class="col-md-3 mb-3">
<label for="validationDefault03">Nombre del Producto</label>
<input name="name" id="nombre" type="text" class="form-control" placeholder="Ej: Remera River Plate" >
</div>
<div class="col-12">
<label for="description" class="form-label">Descipción:</label><br>
<textarea name="description" id="description" class="form-input"></textarea>
</div>
Error display on the the form via EJS:
<% if (typeof errors != 'undefined') { %>
<p style= "color: red">ERROR</p>
</div>
<ul>
<% for(let i = 0; i < errors.length; i++) { %>
<li>
<%= errors[i].msg %>
</li>
<% } %>
</ul>
<% } %>

Related

.save() function not working to update database

I have this working for a different Schema (I can show this code if needed) but when I tried to recreate it for another, it won't update my DB. It's connected to a MongoDB database and this functionality works with another Schema but this one does not
I've hit a dead end and have no idea a this point... Any help would be appreciated!!
Here is the POST controller
console.log("post");
const userId = req.body.userId;
const updatedName = req.body.name;
const updatedPassword = req.body.password;
const updatedEmail = req.body.email;
const updatedSkype = req.body.skype;
const updatedDepartment = req.body.department;
const updatedJobtitle = req.body.jobtitle;
const updatedLinemanager = req.body.linemanager;
const updatedNinumber = req.body.ninumber;
// const updatedJoinDate = req.body.joindate;
// console.log(req.body);
User.findById(userId)
.then((user) => {
isadmin = user.isadmin;
name = updatedName;
password = updatedPassword;
email = updatedEmail;
skype = updatedSkype;
department = updatedDepartment;
jobtitle = updatedJobtitle;
linemanager = updatedLinemanager;
ninumber = updatedNinumber;
joindate = user.joindate;
return user.save();
})
.then((result) => {
console.log("User EDITED!");
res.redirect("/staffdir");
})
.catch((err) => console.log(err));
};
The User model
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const userSchema = new Schema({
isadmin: {
type: Boolean,
required: true,
},
name: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
skype: {
type: String,
required: true,
},
department: {
type: String,
required: true,
},
jobtitle: {
type: String,
required: true,
},
linemanager: {
type: String,
required: true,
},
ninumber: {
type: String,
required: true,
},
joindate: {
type: Date,
required: true,
},
});
module.exports = mongoose.model("User", userSchema);
The Routes
router.get("/add-user", adminController.getAddUser);
router.get("/edit-user/:userId", adminController.getEditUser);
router.get("/edit-user-list", adminController.getEditUserList);
//POST USER
router.post("/add-user", adminController.postAddUser);
router.post("/edit-user/edit-user", adminController.postEditUser);
router.post("/edit-user", adminController.postEditUser);
router.post("/destroy-user", adminController.postDeleteUser);
And the HTML/EJS file
<%- include('../includes/head.ejs') %>
<link rel="stylesheet" href="/css/admin.css" />
<link rel="stylesheet" href="/css/add-user.css" />
<body>
<img src="pozzani.png" alt="pozzani logo" class="pozzanilogo" />
<div class="mainbackground">
<div class="leftcolumn">
<%- include('../includes/signout.ejs') %>
<%- include('../includes/nav.ejs') %>
<%- include('../includes/useful.ejs') %>
</div>
<div class="admin-column">
<h2 class="importanttitle">EDIT USER</h2>
<div class="update-container">
<h3 class="admin-title">Welcome to the USER edit tool</h3>
<p class="admin-content">Please edit forms below to make change. <b>ALL EDITS ARE FINAL!</b></p>
<form class="user-form" action="edit-user" method="POST">
<div class="form-section">
<label for="isadmin">Is Admin?</label>
<select id="isadmin" name="isadmin">
<% if (!user.isadmin) { %>
<option value="false" selected>False</option>
<option value="false">False</option>
<option value="false">False</option>
<option value="false">False</option>
<option value="false">False</option>
<option value="false">False</option>
<option value="true">True - ARE YOU SURE? USER WILL BE ABLE TO EDIT USERS AND UPDATES</option>
<% } else { %>
<option value="true" selected>True - ARE YOU SURE? USER WILL BE ABLE TO EDIT USERS AND UPDATES</option>
<% } %>
</select>
</div>
<div class="form-section">
<label for="name">Name</label>
<input type="text" name="name" id="name" value="<%= user.name %>" >
</div>
<div class="form-section">
<label for="password">Password</label>
<input type="text" name="password" id="password" value="<%= user.password %>">
</div>
<div class="form-section">
<label for="email">Email</label>
<input type="email" name="email" id="email" value="<%= user.email %>">
</div>
<div class="form-section">
<label for="skype">Skype</label>
<input type="text" name="skype" id="skype" value="<%= user.skype %>">
</div>
<div class="form-section">
<label for="department">Department</label>
<input type="text" name="department" id="department" value="<%= user.department %>">
</div>
<div class="form-section">
<label for="jobtitle">Job Title</label>
<input type="text" name="jobtitle" id="jobtitle" value="<%= user.jobtitle %>">
</div>
<div class="form-section">
<label for="linemanager">Line Manager</label>
<input type="text" name="linemanager" id="linemanager" value="<%= user.linemanager %>">
</div>
<div class="form-section">
<label for="ninumber">National Insurance Number</label>
<input type="text" name="ninumber" id="ninumber" value="<%= user.ninumber %>">
</div>
<!-- <div class="form-section">
<label for="joindate">Join Date</label>
<input type="date" name="joindate" id="joindate" value="<%= user.joindate %>">
</div> -->
<input type="hidden" value="<%= user._id %>" name="userId">
<button class="admin-btn" type="submit"><% userId = user._id %>Edit User</button>
</form>
</div>
</div>
</div>
</body>
</html>
Please use findByIdAndUpdate() function instead of findById() and save()
for example;
User.findByIdAndUpdate(userId, {
isadmin: user.isadmin,
name: updatedName,
...
})
.then((result) => {
console.log("User EDITED!");
res.redirect("/staffdir");
})
.catch((err) => console.log(err));

how can I activate the edit button? mongodb

I got this error
CastError: Cast to ObjectId failed for value "details5f9c3b069dc8723528c64cc8" at path "_id" for model "Book"
the edit and delete button are not activated.
Help me to figure it out please. this is /routes/books.js
and what else do I upload here?
// GET edit an existing Book
router.get('/:id', (req, res, next) => {
let id = req.params.id;
book.findById(id, (err, bookToEdit) => {
if(err) {
console.log(err);
//res.end(err);
} else {
//show the edit view
res.render('books/details', {title: 'Edit Book', books: bookToEdit})
}
});
});
// POST and update the document
router.post('/:id', (req, res, next) => {
let id = req.params.id
let updatedBook = book({
_id: id,
title: req.body.title,
description: req.body.description,
price: req.body.price,
author: req.body.author,
genre: req.body.genre
});
book.updateOne({_id: id}, updatedBook, (err) => {
if(err) {
console.log(err);
res.end(err);
} else {
// refresh
res.redirect('/books');
}
});
});
// GET - process the delete by user id
router.get('/delete/:id', (req, res, next) => {
let id = req.params.id;
book.remove({_id: id}, (err) => {
if(err) {
console.log(err);
res.end(err);
} else {
// refresh
res.redirect('/books');
}
});
});
This is /books/details.ejs
<div class="container">
<div class="row">
<form class="form" method="post">
<div class="form-group">
<label for="TitleTextField">Title</label>
<input type="text" class="form-control" id="TitleTextField"
placeholder="Book Title" name="title" value="<%= books.Title %>" required>
</div>
<div class="form-group">
<label for="AuthorTextField">Author</label>
<input type="text" class="form-control" id="AuthorTextField"
placeholder="Book Author" name="author" value="<%= books.Author %>" required>
</div>
<div class="form-group">
<label for="PriceTextField">Price</label>
<input type="text" class="form-control" id="PriceTextField"
placeholder="Book Price" name="price" value="<%= books.Price %>" required>
</div>
</div>
</div>
and this is /books/indexejs
<% include ../partials/header.ejs %>
<!-- MAIN CONTENT -->
<div class="container">
<div class="row">
<!--Add-->
<i class="fa fa-plus"></i> Add a book
<br>
<br>
<div class="table-responsive">
<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th>Title</th>
<th class="text-center">Author</th>
<th class ="col-4">Price</th>
<th class="text-center">EDIT</th>
<th class="text-center">DELETE</th>
</tr>
</thead>
<tbody>
<% for (let count = 0; count < books.length; count++) { %>
<tr>
<td><%= books[count].Title %></td>
<td class="text-center"><%= books[count].Author %></td>
<td class="text-center">$<%= books[count].Price %></td>
<!--EDIT-->
</td>
<td class="text-center">
<a href="/books/edit<%= books[count].id %>" class="btn btn-primary btn-sm">
<i class="fas fa-pencil-alt"></i> Edit</a>
</td>
<!--DELETE-->
<td class="text-center">
<a href="/books/delete<%= books[count].id %>" class="btn btn-danger btn-sm">
<i class="fas fa-trash-alt"></i> Delete</a></td>
</td>
</tr>
<% } %>
</tbody>
</table>
</div>
</div>
</div>
</div>
<% include ../partials/footer.ejs %>
this is /models/books.js
let mongoose = require('mongoose');
let Book = mongoose.Schema({
Title: String,
Description: String,
Price: Number,
Author: String,
Genre: String
},
{
collection: "books"
});
module.exports = mongoose.model('Book', Book);
hope these are helpful to fix the problems
You have an error that said that book.find and book.delete need an ObjectId as parameter. And details5f9c3b069dc8723528c64cc8 is not a valid ObjectId for Mongo.
Just read the error message !
Edition
Maybe you face this problem because you made a little mistake with resources, using same http POST to create and edit, giving the :id in path in both case.
If you have a POST / (no id in path) method to create books, letting mongodb generate ids, and have a PATCH (or PUT) /:id method to update those books, you probably will not have this kind of error anymore.
It will maybe sounds like stupid duplication but as your app will grow, you certainly will need to add some specific security rules.
Also, if I remember mongoose correctly, you're not supposed update the _id in second parameter for updateOne.
//no _id present in updatedBook
book.updateOne({_id: id}, updatedBook, (err) => { };
The default key of a document in MongoDB is _id who set an ObjectId in it.
ObjectId is a unique key who contained from some meaningful base on date and time (you can convert objectId to date).
You can read more about it here.
And your problem, it's really easy. You concat your ObjectId with details as you can see in the error.
details5f9c3b069dc8723528c64cc8 => 5f9c3b069dc8723528c64cc8

In HTML, name="object[prop]" doesn't seem to work

When I console.log the req.body it gives me:
[Object: null prototype] {
'shoe[name]': 'Shoe Name',
'shoe[description]': '',
'shoe[pictures]': '',
'shoe[collections]': 'Shoe Collection'
}
But when I console.log req.body.shoe It prints undefined,
been breaking my head for a few days now
The form:
<form action="/shoes/" method="post">
<input type="text" name="shoe[name]" placeholder="Name of the shoe">
<textarea name="shoe[description]" cols="30" rows="10"></textarea>
<input type="file" name="shoe[pictures]">
<input type="text" name="shoe[collections]">
<input type="submit" value="Post the Shoe">
</form>
Shoe Model:
const mongoose = require('mongoose');
const shoeSchema = new mongoose.Schema({
name: { type: String, unique: true },
description: String,
displayPicture: mongoose.Schema.Types.ObjectId,
pictures: [ { type: mongoose.Schema.Types.ObjectId } ],
collections: [ { type: mongoose.Schema.Types.ObjectId, unique: true } ],
dateOfPublish: { type: Date, default: Date.now },
comments: [
{
userId: { type: mongoose.Schema.Types.ObjectId, unique: true, ref: 'Comment' }
}
]
});
module.exports = mongoose.model('Shoe', shoeSchema);
Node.js + Express create route:
//Create
router.post('/', (req, res) => {
console.log(req.body.shoe);
Shoe.create(req.body.shoe, (err, shoe) => {
if (err) {
console.log(err);
} else {
return res.redirect('/');
}
});
});
You cannot implement the below way the html part
<input type="file" name="shoe[pictures]">
You yourself is seeing that
[Object: null prototype] {
'shoe[name]': 'Shoe Name',
'shoe[description]': '',
'shoe[pictures]': '',
'shoe[collections]': 'Shoe Collection'
}
'shoe[pictures]' is the entire key and you are only accessing req.body.shoe
First your entire HTML need to be changed.
<form action="/shoes/" method="post">
<input type="text" name="name" placeholder="Name of the shoe">
<textarea name="description" cols="30" rows="10"></textarea>
<input type="file" name="pictures">
<input type="text" name="collections">
<input type="submit" value="Post the Shoe">
</form>
And then in backend in req.body object you will receive all the properties name,description,pictures,collections
After that you can access
req.body.name
req.body.description etc
Then in backend you need to define
var shoe = {...req.body}
and then you can use shoe object
<% include ../partials/header %>
<div class="row">
<div class="col-md-4">
<h2><%= user.firstName + " " + user.lastName %></h2>
<div class="thumbnail">
<img src="<%= user.avatar %>" alt="user profile image">
<div class="caption"><%= user.email %></div>
</div>
</div>
<div class="col-md-8">
``` <h3><%= user.username %>'s campgrounds</h3>
<% campgrounds.forEach(campground => { %>
<div class="col-md-4 col-sm-6">
<div class="thumbnail card">
<img src="<%= campground.image.url %>" alt="<%= campground.name %>">
<div class="caption">
<h4 class="caption"><%= campground.name %></h4>
</div>
</div>
</div>
<% }); %>
</ul>
</div>
Edit Profile
</div>
<% include ../partials/footer %>
Can you see that %include is written here. if that statement is not present in your code it will not work. That is what i am trying to explain from that time
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>New Shoe</title>
</head>
<body>
<form action="/shoes/" method="post">
<input type="text" name="shoe[name]" placeholder="Name of the shoe">
<textarea name="shoe[description]" cols="30" rows="10"></textarea>
<input type="file" name="shoe[pictures]" value="Shoe Pictures">
<!-- tick the display pic -->
<input type="text" name="shoe[collections]">
<input type="submit" value="Post the Shoe">
</form>
</body>
</html>
In your there is nothing like that
The problem was with the body-parser, needed to use the qs library (true) instead of querystring(false) in the following line:
app.use(require('body-parser').urlencoded({ extended: true }));
originally extended was set to false.
for more info refer to this link

How to create self referencing MongoDB schema and post routes using nodejs?

I am trying to create parent-child like nested system where child has same schema as of parent.Below is my parent schema, here children refers to the parentSchema again,
var mongoose = require("mongoose");
var parentSchema = new mongoose.Schema({
name: String,
children:[
{
ref: this
}
],
});
module.exports = mongoose.model("Parent", parentSchema);
Routes looks like this
app.get("/", function(req, res){
Parent.find({}).populate("children").exec(function(err, allParents){
if(err){
console.log(err);
}else{
res.render("index",{parents: allParents});
}
});
});
app.post("/", function(req,res){
var name = req.body.name;
var desc = req.body.desc;
var newParent = {name: name, description: desc}
Parent.create(newParent, function(err, newlyCreate){
if(err){
console.log(err);
}else{
res.redirect("/");
}
});
});
app.post("/:id", function(req, res){
Parent.findById(req.params.id, function(err, parent){
if(err){
console.log(err);
res.redirect("/");
}else{
parent.children.push(req.body.child);
parent.save();
console.log(parent.children);
res.redirect("/");
}
});
});
The problem is when I send data from form to post route it prints it but after pushing it into parent.children and then printing parent.children is shows null. Where is the problem???
EJS page looks like below:-
<form action="/" method="POST">
<div class="form-group">
<input type="text" name="name" placeholder="Name">
</div>
<div class="form-group">
<input type="text" name="desc" placeholder="Description">
</div>
<div class="form-group">
<button class=btn-primary btn-block">Submit</button>
Go Back
</div>
</form>
<div class="row">
<% parents.forEach(function(module){%>
<ul class="list-group">
<li class="list-group-item" style="margin-bottom: 5%;">
<h2><%= module.name%></h2>
<%= module.description %>
<% console.log(module.children) %>
<%module.children.forEach(function(node){%>
<% console.log(node) %>
<%});%>
<div class="container">
<div class="row">
<div>
<form action="/<%= module._id %>" method="POST">
<div class="form-group">
<input type="text" name="name" placeholder="Name">
</div>
<div class="form-group">
<input type="text" name="desc" placeholder="Description">
</div>
<button>Submit</button>
</form>
</div>
</div>
</div>
</li>
</ul>
</div>
<% }); %>
</div>
Can anyone tell where is the problem in above code or can anyone suggest any other way to make this type of parent-child structure????
It seems that parent.save() is asynchronus. Maybe you can try this instead.
parent.save().then(()=>{
console.log(parent.children);
res.redirect("/");
});
or you can use async-await after putting async before function definition,
await parent.save();
console.log(parent.children);
res.redirect("/");
Please do write in comment if problem still persists.

Invalid attributes sent to model. Validation issues

I'm using the validation service from https://gist.github.com/basco-johnkevin/8436644 and currently having some issues upon submission of my data. It seems like maybe the validation service doesn't like NaN values or I'm possibly missing something. Any ideas?
My form:
<div class="container">
<form action="/standardplacement/create" method="POST" role="form">
<div class="row-fluid">
<h2 class="form-signin-heading">Create a <em>Standard Media</em> placement</h2>
<% if (req.session.flash && req.session.flash.error) { %>
<% var errors = req.flash('error') %>
<div class="alert alert-danger">
<button type="button" class="close" aria-hidden="true" data-dismiss="alert">×</button>
<ul>
<% Object.keys(errors).forEach(function(error) { %>
<% Object.keys(errors[error]).forEach(function(error_message) { %>
<% Object.keys(errors[error][error_message][0]).forEach(function(error_message_res) { %>
<li><%- errors[error][error_message][0][error_message_res] %></li>
<% }); %>
<% }); %>
<% }); %>
</ul>
</div>
<% var t_results = req.flash('temp_results'); %>
<% if(t_results[0]){ %>
<%
t_results = t_results[0];
sails.log.info("Results Restored");
%>
<% } %>
<% } %>
</div>
<div class="row-fluid">
<div class="form-group">
<label for="pName">Placement Name</label>
<input type="text" name="name" id="pName" class="form-control" required="required" title="Name" placeholder="12/27 Homepage 300x250 Banner" />
</div>
</div>
<div class="row-fluid">
<blockquote>
<p class="lead">General Specifications</p>
</blockquote>
</div>
<div class="row-fluid">
<div class="form-group row">
<div class="col-xs-4">
<label for="pWidth">Width</label>
<div class="input-group">
<input type="integer" name="width" id="pWidth" class="form-control" title="Width (in PX)" placeholder="300" />
<div class="input-group-addon">px</div>
</div>
</div>
<div class="col-xs-4">
<label for="pHeight">Height</label>
<div class="input-group">
<input type="integer" name="height" id="pHeight" class="form-control" title="Height (in PX)" placeholder="250" />
<div class="input-group-addon">px</div>
</div>
</div>
</div>
</div>
<br/>
<div class="row-fluid">
<div class="form-group">
<button type="submit" class="btn btn-lg btn-primary" type="submit">Create Placement</button>
<input type="hidden" name="_csrf" value="<%= _csrf %>" />
</div>
</div>
</form>
</div>
My controller:
create: function(req, res){
StandardPlacement.create( req.params.all() ).exec( function (error, placement) {
sails.log( req.params.all() );
if(error) {
sails.log(error);
sails.log(error.ValidationError);
if(error.ValidationError) {
error_object = ValidationService.transformValidation(StandardPlacement, error.Validation);
sails.log.warn(error_object);
res.send({result: false, errors: error_object});
}
}
// After successfully creating the placement
// redirect the user to the show action
res.redirect('/standardplacement/show/' + placement.id);
});
},
My model:
module.exports = {
attributes: {
name: {
type: 'string',
minLength: 2,
required: true
},
width: {
type: 'integer',
required: true
},
height: {
type: 'integer',
required: true
}
},
validation_messages: {
name: {
required: 'You must supply a valid name for the placement. If you do not have a specific name, make up one.',
minLength: 'The name must be more than one character long.'
},
width: {
required: 'You must supply a width value in pixels.'
},
height: {
required: 'You must supply a height value in pixels.'
},
}
};
The service in api/services/ValidationService.js:
/**
* Takes a Sails Model object (e.g. User) and a ValidationError object and translates it into a friendly
* object for sending via JSON to client-side frameworks.
*
* To use add a new object on your model describing what validation errors should be translated:
*
* module.exports = {
* attributes: {
* name: {
* type: 'string',
* required: true
* }
* },
*
* validation_messages: {
* name: {
* required: 'you have to specify a name or else'
* }
* }
* };
*
* Then in your controller you could write something like this:
*
* var validator = require('sails-validator-tool');
*
* Mymodel.create(options).done(function(error, mymodel) {
* if(error) {
* if(error.ValidationError) {
* error_object = validator(Mymodel, error.Validation);
* res.send({result: false, errors: error_object});
* }
* }
* });
*
* #param model {Object} An instance of a Sails.JS model object.
* #param validationErrors {Object} A standard Sails.JS validation object.
*
* #returns {Object} An object with friendly validation error conversions.
*/
exports.transformValidation = function(model, validationError) {
sails.log.info("Validating Submission");
var validation_response = {};
var messages = model.validation_messages;
validation_fields = Object.keys(messages);
validation_fields.forEach(function(validation_field) {
if(validationError[validation_field]) {
var processField = validationError[validation_field];
processField.forEach(function(rule) {
if(messages[validation_field][rule.rule]) {
if(!(validation_response[validation_field] instanceof Array)) {
validation_response[validation_field] = new Array();
}
var newMessage = {};
newMessage[rule.rule] = messages[validation_field][rule.rule];
validation_response[validation_field].push(newMessage);
}
});
}
});
sails.log.info("Validation Complete!");
return validation_response;
};
The error:
error: Sending 500 ("Server Error") response:
TypeError: Cannot read property 'width' of undefined
at /Users/me/Sites/specs/api/services/ValidationService.js:49:22
at Array.forEach (native)
at Object.exports.transformValidation (/Users/me/Sites/specs/api/services/ValidationService.js:47:21)
at /Users/me/Sites/specs/api/controllers/StandardPlacementController.js:34:39
at bound (/usr/local/lib/node_modules/sails/node_modules/lodash/dist/lodash.js:957:21)
at applyInOriginalCtx (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/utils/normalize.js:416:80)
at wrappedCallback (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/utils/normalize.js:326:16)
at _normalizeCallback.callback.error (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/node-switchback/lib/normalize.js:42:31)
at _switch (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/node-switchback/lib/factory.js:33:28)
at /usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/query/dql/create.js:51:22 [TypeError: Cannot read property 'width' of undefined]
After talking to some folks in #sailsjs, I figured it out. Ended up removing the create method from the controller. Updated api/responses/badRequest.js with the following.
In badRequest.js:
var referringView = req.header('Referer').replace(req.protocol + "://" + req.host + ":" + req.port + '/', '');
var errors = data.invalidAttributes;
var error_object = {};
if(errors) {
error_object = ValidationService.transformValidation(StandardPlacement, errors);
return res.view(referringView, {result: false, errors: error_object});
}
In View (read/show the errors):
<% if (res.locals && res.locals.errors) { %>
<% var errors = res.locals.errors; %>
<div class="alert alert-danger">
<button type="button" class="close" aria-hidden="true" data-dismiss="alert">×</button>
<ul>
<% Object.keys(errors).forEach(function(error) { %>
<% Object.keys(errors[error]).forEach(function(error_message) { %>
<% sails.log(errors[error][error_message]); %>
<% Object.keys(errors[error][error_message]).forEach(function(error_message_res) { %>
<li><%- errors[error][error_message][error_message_res] %></li>
<% }); %>
<% }); %>
<% }); %>
</ul>
</div>
<% var t_results = req.flash('temp_results'); %>
<% if(t_results[0]){ %>
<%
t_results = t_results[0];
sails.log.info("Results Restored");
%>
<% } %>
<% } %>
Simply add below line of code to see the response of your error
SomeModel.create({}).then(function(){
}).catch(function(err){
console.log(err.ValidationError);
})

Categories