ValidatorError on adding records - javascript

I am trying to add a record to my mongodb database. I am sure that I am providing correct values, although mongoose is considering them missing. Here's my Schema -
var mongoose = require('mongoose');
var SocketUserSchema = new mongoose.Schema({
name: String,
username: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
},
devices: [{
name: String,
platform: String
}],
first_ip: {
type: String,
default: "0.0.0.0"
},
last_login_ip: {
type: String,
default: "0.0.0.0"
},
added_at: {
type: Date,
default: Date.now
},
});
module.exports = mongoose.model('SocketUser', SocketUserSchema);
Here's my create code snippet -
console.log('registered triggered ' + data);
/*var jsonData = data;
jsonData.first_ip = clientIpAddress;
jsonData.last_login_ip = clientIpAddress;*/
var user = new SocketUser({
username: data.username,
password: data.password,
devices: data.devices,
first_ip: clientIpAddress,
last_login_ip: clientIpAddress
});
SocketUser.create(user, function(err, post) {
if (err) {
console.log('error',err);
} else {
console.log('success');
}
});
Here's the sample user data I am sending -
{
"username": "nexus",
"password": "noob",
"devices": [
{
"name": "Nexus",
"platform": "android"
}
]
}
And here's the error I am getting -
{
"message": "SocketUser validation failed",
"name": "ValidationError",
"errors": {
"username": {
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "username"
},
"message": "Path `username` is required.",
"name": "ValidatorError",
"kind": "required",
"path": "username"
},
"password": {
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "password"
},
"message": "Path `password` is required.",
"name": "ValidatorError",
"kind": "required",
"path": "password"
}
}
}
As you can see, username and password both fields are there in the data, but still it's giving error. I have tried sending data json directly to Create method and also tried save method too. Both gives same error. Is there anything I am missing here?
Update:
I tried validating the record, before adding it to database and it gave same error -
user.validate(function(err) {
if (err) {
console.log("error "+err.message+"\nFull error: "+JSON.stringify(err));
}
else {
}
});
registered triggered {"username":"nexus","password":"noob","devices":[{"name":"N
exus","platform":"android"}]}
error SocketUser validation failed
Full error: {"message":"SocketUser validation failed","name":"ValidationError","
errors":{"password":{"properties":{"type":"required","message":"Path `{PATH}` is
required.","path":"password"},"message":"Path `password` is required.","name":"
ValidatorError","kind":"required","path":"password"},"username":{"properties":{"
type":"required","message":"Path `{PATH}` is required.","path":"username"},"mess
age":"Path `username` is required.","name":"ValidatorError","kind":"required","p
ath":"username"}}}
I am unable to find the issue with username and password. I want these fields as required fields for obvious reasons.

I found the issue, I checked if I am getting data.username and data.password properly or not. They were resulting in undefined. Then I realized that the data is actually a string, not an object. So I parsed it into json and then I got it working. Here's the code to do it, in case somebody get stuck at the same issue -
data = JSON.parse(data);

Related

Yup: How to access the "inner" propriety in ValidationError() method

Yup contain a method name validationError whose one of properties is "inner". Accordingly with the documentation:
in the case of aggregate errors, inner is an array of ValidationErrors
throw earlier in the validation chain. When the abortEarly option is
false this is where you can inspect each error thrown, alternatively,
errors will have all of the messages from each inner error.
However, it's properly working is not quite clear to me. How exactly I do to access this property and use it in my code.
Here, I'm trying to use in this application but it seems not working.
function validator (req, res, next) {
yup.setLocale({
mixed: {
default: 'Não é válido',
}
});
const schema = yup.object().shape({
name: yup.string().required("Legendary name is required"),
type: yup.string().required("Legendary type is required"),
description: yup.string().required("Legendary description is required").min(10)
});
let messageError = new yup.ValidationError([`${req.body.name}`, `${req.body.type}`, `${req.body.description}`]);
if(!schema.isValidSync(req.body, {abortEarly: false})) {
return res.status(400).json(messageError.inner);
}
When I run it with insomnia, I get a empty array only.
Can someone help me with this, please ?
ValidationError is thrown is by the validate* methods (validate, validateSync, validateAt, and validateSyncAt) when the validation fails. isValidSync returns a boolean and doesn't throw any errors. Use validateSync and add a catch block to access the validation errors.
messageError.inner returns an empty array since messageError is a standalone ValidationError object which isn't associated with the schema in any way.
try {
schema.validateSync(req.body, { abortEarly: false })
} catch (err) {
// err is of type ValidationError
return res.status(400).json(err.inner)
}
curl -s -X POST http://localhost:5000/test | jq
[
{
"name": "ValidationError",
"path": "name",
"type": "required",
"errors": [
"Legendary name is required"
],
"inner": [],
"message": "Legendary name is required",
"params": {
"path": "name"
}
},
{
"name": "ValidationError",
"path": "type",
"type": "required",
"errors": [
"Legendary type is required"
],
"inner": [],
"message": "Legendary type is required",
"params": {
"path": "type"
}
},
{
"name": "ValidationError",
"path": "description",
"type": "required",
"errors": [
"Legendary description is required"
],
"inner": [],
"message": "Legendary description is required",
"params": {
"path": "description"
}
}
]

Loopback cannot send dynamic values in email

I have a contact form where i can able to save the data in the database using loopback3. I need to send an email also so i have added the email connector for this module, but i can able to send only the static values in the mail. How to get the dynamic values in contact.js file and send through email.
contact.json
{
"name": "contact",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"id": {
"type": "number"
},
"name": {
"type": "string",
"required": true
},
"email": {
"type": "string",
"required": true
},
"subject": {
"type": "string",
"required": true
},
"message": {
"type": "string",
"required": true
},
"inserted_date": {
"type": "string"
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
contact.js
'use strict';
const app = require('../../server/server');
module.exports = function(Contact) {
Contact.afterRemote('create', function(context, remoteMethodOutput, next) {
next();
Contact.app.models.Email.send({
to: 'lakshmipriya.l#company.com',
from: 'lakshmipriya.l#gmail.com',
subject: 'my subject',
text: 'my text',
html: 'my <em>html</em>'
}, function(err, mail) {
console.log('email sent!');
cb(err);
});
});
};
How to send an email with dynamic values, can anyone tell me how to fetch the contact.json values and send to contact.js file .
You can access the model instance through the context object, which transports the data. You can read more on it here: https://loopback.io/doc/en/lb2/Remote-hooks.html#ctxresult
So to send the email to the contact that has been created:
Contact.app.models.Email.send({
to: context.result.email,
from: 'lakshmipriya.l#gmail.com',
subject: 'my subject',
text: 'my text',
html: 'my <em>html</em>'
}, function(err, mail) {
console.log('email sent!');
cb(err);
});
});

JSON schema + relative JSON-pointers: how to verify "confirm password" field

Here's my JSON Schema:
{
"required": [
"username",
"password",
"confirmPassword"
],
"properties": {
"username": {
"minLength": 3,
"type": "string"
},
"password": {
"minLength": 6,
"type": "string"
},
"confirmPassword": {
"const": {
"$data": "1/password"
},
"type": "string"
}
},
"type": "object"
}
Here's my data:
{
"username": "abc",
"password": "asdfasdf",
"confirmPassword": "asdfasdf"
}
You can copy-paste those into this online validator to see what happens.
The confirmPassword field is failing validation with error message:
Value "asdfasdf" does not match const.
I believe there is a problem with my relative JSON pointer but I can't figure out what the correct syntax is.
AFAICT, 1/password means "go up one level, and then check the password property" but that doesn't appear to be the case. What's correct syntax?
The specific implementation I'm using is AJV which says it does support relative-JSON-pointers.
Turns out the only problem was that I forgot to set the $data option to true. e.g.
const ajv = new Ajv({
allErrors: true,
$data: true,
});

ValidatorError JSON

Upon using Postman when I try to POST an answer to the questions id it gives a 400 Bad Request error and it seems to be a validator error. Here is the POST request JSON data I am sending. It has been a long day and still havent been able to figure this out. Below I am listing my Schema and routes.
I am also using packages such as body-parser and node-restful
{
"aTitle": "THIS IS A TEST",
"aBody": "This is a body test"
}
{
"message": "Questions validation failed",
"name": "ValidationError",
"errors": {
"answers.aBody": {
"message": "Path `answers.aBody` is required.",
"name": "ValidatorError",
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "answers.aBody"
},
"kind": "required",
"path": "answers.aBody"
},
"answers.aTitle": {
"message": "Path `answers.aTitle` is required.",
"name": "ValidatorError",
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "answers.aTitle"
},
"kind": "required",
"path": "answers.aTitle"
},
"qBody": {
"message": "Path `qBody` is required.",
"name": "ValidatorError",
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "qBody"
},
"kind": "required",
"path": "qBody"
},
"qTitle": {
"message": "Path `qTitle` is required.",
"name": "ValidatorError",
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "qTitle"
},
"kind": "required",
"path": "qTitle"
}
}
}
// Dependencies
var restful = require('node-restful');
// Database
var mongoose = restful.mongoose;
var Schema = mongoose.Schema;
// Question Schema
var QuestionSchema = new Schema({
qTitle: {
type: String,
required: true
},
qBody: {
type: String,
required: true
},
created_at: {
type: Date
},
updated_at: {
type: Date
},
// Relationship to the Question or child of the question
answers: {
aTitle: {
type: String,
required: true
},
aBody: {
type: String,
required: true
},
created_at: Date,
updated_at: Date
}
});
// Export the question schema
module.exports = restful.model('Questions', QuestionSchema);
'use strict';
var express = require('express');
var router = express.Router();
var Question = require('../models/question');
Question.methods(['get', 'put', 'post', 'delete']);
Question.register(router, '/questions');
Question.register(router, '/questions/:id/answers');
// Exports the router
module.exports = router;
According to the error message and the question schema (look at the ones that have required: true), the POSTed request JSON data you need to send is at least like this:
{
"qTitle": "this is question title",
"qBody": "this is question body",
"answers": {
"aTitle": "THIS IS A TEST",
"aBody": "This is a body test"
}
}

Node.js/Mongo schema validation error regardless of POST data

I have mongo and node playing together on AWS EC2. Node (w/ Express) can connect to Mongo so to start with I've setup a schema with two required fields "sesh" and "location".
This is the javascript that gets called for the post query:
app.post('/spotters', function(req,res){
var newSesh = new modelentry(req.body);
newSesh.save(function(err){
if(err)
res.send(err);
res.json(req.body);
});
});
modelentry is the schema of course.
I'm trying to POST the following raw/json data using Postman
{
sesh: 1,
location: [1,2]
}
However I always recieve a validation failed message, as follows:
{
"message": "hotuser validation failed",
"name": "ValidationError",
"errors": {
"location": {
"message": "Path `location` is required.",
"name": "ValidatorError",
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "location"
},
"kind": "required",
"path": "location"
},
"sesh": {
"message": "Path `sesh` is required.",
"name": "ValidatorError",
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "sesh"
},
"kind": "required",
"path": "sesh"
}
}
}
I have looked at a lot of example code and tried tinkering with the functions in app.post but I'm not making any progress. I would really appreciate any help.

Categories