the value of props.record.DataUpdate.draft
{"FirstName": "This is my firstname","MiddleName": "This is my middlename","LastName": "this is my lastname"}
let newData = JSON.parse(props.record.DataUpdate.draft)
console.log(newData)
{
"FirstName": "This is my firstname",
"MiddleName": "This is my middlename",
"LastName": "this is my lastname"
}
this is my database looks like
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
tableNameToBeUpdated: {
type: Sequelize.STRING,
},
tableIdToBeUpdated: {
type: Sequelize.STRING,
},
draft: {
type: Sequelize.JSON,
},
CreatedDate: {
type: Sequelize.DATE,
},
LastUpdateDate: {
type: Sequelize.DATE,
},
status: {
type: Sequelize.STRING,
},
what I want here is to get the label (Fistname,Lastname,Middlename) with there perspective value,
note the label can be change it depends on the string that saves on draft column
how to achieve that?
Something like that:
const jsonString = {"FirstName": "This is my firstname","MiddleName": "This is my middlename","LastName": "this is my lastname"}
for (var key in jsonString) {
console.log(key + " -> " + jsonString[key]);
}
This gives me the Output:
'FirstName -> This is my firstname'
'MiddleName -> This is my middlename'
'LastName -> this is my lastname'
Edit:
Ok i took the example form your post (without the single quotes). Then just do what you posted and then use the for loop:
const jsonString = '{"FirstName": "This is my firstname","MiddleName": "This is my middlename","LastName": "this is my lastname"}'
const jsonObject = JSON.parse(jsonString)
for (var key in jsonObject) {
console.log(key + " -> " + jsonObject[key]);
}
Related
Main Model
{
name: {
type: String,
trim: true,
required: true
},
carModels: [{
type: ObjectId,
ref: 'CarModel'
}]
}
Second Model
{
name: {
type: String,
trim: true,
required: true
},
carModels: [
{
type: ObjectId,
ref: 'CarModel'
}
]
},
Third Model
{
name: {
type: String,
trim: true,
required: true
}
},
Here i am trying to insert the data like this
{
"name": "test",
"phoneNumber": "0123456789",
"email": "m#m.com",
"carMakes": [{
"name": "BMW",
"carModels": [{
"_id": "some id"
}]
}]
}
and it giving me error like
carMakes.0: Cast to [ObjectId] failed for value
here is the create function
export const create = async data => {
const result = await Booking(data).save();
return result;
};
Can anyone tell what I am missing here ..i am learning nodejs
i think the problem is with the _id that you're passing to carModel and since you set the type to ObjectId it has to be in a valid format "either 12 byte binary string, or a 24 hex byte string" and "some id" is not the valid one if you're sending that.
you can check if your id is valid with isValidObjectId() function.
or you can easily generate an ObjectId:
var mongoose = require('mongoose');
var id = new mongoose.Types.ObjectId();
I'm trying to use Yup along with Formik in my react form. The form fields are going to be dynamic so as their validations.
export const formData = [
{
id: "name",
label: "Full name",
placeholder: "Enter full name",
type: "text",
required: true,
value: "User name",
values: [],
validations: [
{
type: "minLength",
value: "5",
error_message: "name should be atleast 5 char long"
},
{
type: "maxLength",
value: "10",
error_message: "name should be atleast 5 char long"
}
]
},
{
id: "email",
label: "Email",
placeholder: "Email",
type: "text",
required: true,
value: "email",
values: [],
validations: [
{
type: "minLength",
value: "5",
error_message: "name should be atleast 5 char long"
},
{
type: "maxLength",
value: "10",
error_message: "name should be atleast 5 char long"
},
{
type: "email",
error_message: "Valid email"
}
]
},
{
id: "phoneNumber",
label: "phone number",
type: "text",
required: true,
value: "7878787878",
values: [],
validations: [
{
type: "minLength",
value: "5",
error_message: "name should be atleast 5 char long"
},
{
type: "maxLength",
value: "10",
error_message: "name should be atleast 5 char long"
},
{
type: "required",
error_message: "phone number is required"
}
]
},
{
id: "total",
label: "Total People in Family",
placeholder: "family members count",
type: "text",
required: false,
value: "1",
values: [],
validations: [
{
type: "minLength",
value: "1",
error_message: "there should be atleast 1 family member"
},
{
type: "maxLength",
value: "5",
error_message: "max family members can be 5"
}
]
}
]
let validateSchema = yup.object().shape({
name: yup.string().required("name is required"),
email: yup.string().email(),
phoneNumber: yup.number().min(10, "minium 10 numbers"),
total: yup
.number()
.min(1, "minium 1 member")
.max(5, "max 5 member")
.required("member is required") });
What I'm currently doing is iterating over the above array and calling the corresponding React form components.
Validation is currently handled by Yup. I'm aware that you can create static Yup validation schema like above `validateSchema' variable.
Now I want to create this validation schema depending upon the values
in the formData.validation array. I tried some of the ways in this
codesandbox but still unable to figure it out. Also, I looked
into the Yup.lazy but it seems highly confusing to me.
Any help will be appreciated :)
Codesandbox
In case someone is trying to create yupschema on the fly. With some help, I was able to do it.
import * as yup from "yup";
export function createYupSchema(schema, config) {
const { id, validationType, validations = [] } = config;
if (!yup[validationType]) {
return schema;
}
let validator = yup[validationType]();
validations.forEach(validation => {
const { params, type } = validation;
if (!validator[type]) {
return;
}
console.log(type, params);
validator = validator[type](...params);
});
schema[id] = validator;
return schema;
}
Codesandbox
If you're looking for more functionality, consider schema-to-yup.
But #vijayscode's answer is super handy. Here's an attempt to extend their example to include when conditions:
import * as yup from "yup";
function createYupSchema(schema, config) {
const { id, validationType, validations = [] } = config;
if (!yup[validationType]) {
return schema;
}
let validator = yup[validationType]();
validations.forEach((validation) => {
const { params, type } = validation;
if (!validator[type]) {
return;
}
if (type === "when") {
const { is, then, otherwise } = params[1];
let whenParams = {};
whenParams.is = is;
whenParams.then = (schema) => schema[then[0].type](...then[0].params);
if (otherwise) {
whenParams.otherwise = (schema) =>
schema[otherwise[0].type](...otherwise[0].params);
}
validator = validator["when"](params[0], whenParams);
} else {
validator = validator[type](...params);
}
});
schema[id] = validator;
return schema;
}
And define your config like so:
const myConfig = [
{
id: "isBig",
validationType: "boolean",
},
{
id: "count",
validationType: "number",
validations: [
{
type: "when",
params: [
"isBig",
{
is: true,
then: [
{
type: "min",
params: [5],
},
],
otherwise: [
{
type: "min",
params: [0],
},
],
},
],
},
],
},
];
const schema = myConfig.reduce(createYupSchema, {});
const validateSchema = yup.object().shape(schema);
Apologies if this has been answered before, I have checked other answers and can't work it out from those.
I have a set of information that I would like placed into an array named "teamDetails". Here is the relevant /post item from server.js:
app.post('/create', (req, res) => {
console.log('Post command received');
console.log(req.body);
console.log(req.body.data.teamDetails[0]);
//We need to push the variable below, 'teamDetails', as an object into an array of the same name
var teamDetailsObj = {
// Modified for Postman
"teamName": req.body.data.teamDetails[0].teamName,
"teamNameShort": req.body.data.teamDetails[0].teamNameShort,
"teamfounded": req.body.data.teamDetails[0].teamFounded,
"teamHome": req.body.data.teamDetails[0].teamHome
};
console.log(teamDetails);
var newTeam = new Team({
"data.added": new Date(),
"data.entry": req.body.data.entry
});
newTeam.save().then((doc) => {
console.log("This is newTeam.data: " + newTeam.data);
console.log("This is teamDetailsObj: " + teamDetailsObj);
newTeam.data.teamDetails.push(teamDetailsObj);
var teamId = doc.id;
res.render('success.hbs', {teamId});
console.log("Team Added - " + teamId);
}, (e) => {
res.status(400).send(e);
});
});
Here is my team.js model:
var mongoose = require('mongoose');
var ObjectID = mongoose.Schema.Types.ObjectId;
var Mixed = mongoose.Schema.Types.Mixed;
var Schema = mongoose.Schema;
var Team = mongoose.model('Team', {
data: {
entry: {
type: String,
default: "USER.INPUT"
},
added: {
type: Date,
default: Date.Now
},
teamDetails: [
{
teamName: {
type: String,
trim: true,
required: true,
default: "First Team"
},
teamNameShort: {
type: String,
trim: true,
uppercase: true,
maxlength: 3,
required: true
},
teamFounded: {
type: Number,
maxlength: 4
},
teamHomeCity: {
type: String
}
}
]
}
});
module.exports = {Team};
Lastly, the sample data I'm trying to inject via Postman:
{
"data": {
"entry": "Postman.Entry",
"teamDetails": [
{
"teamName": "Test Teamname",
"teamNameShort": "TTN",
"teamFounded": "1986",
"teamHome": "London",
"players": [
{
"player1Name": "Test Player 1",
"player1Position": "Forward",
"player1Nationality": "GBR"
},
{
"player2Name": "Test Player 2",
"player2Position": "Defender",
"player2Nationality": "UKR"
},
{
"player3Name": "Test Player 3",
"player3Position": "Goaltender",
"player3Nationality": "IRL",
"captain": true
}
],
"coachingStaff": {
"headCoach": "Derp McHerpson",
"teamManager": "Plarp McFlarplarp"
}
}
]
}
}
(Disregard the players section, it's another kettle of fish)
As a result of using my code above, the resulting entry for teamDetails is just an empty array. I just can't get my code to push the teamDetailsObj into it.
Any help anyone can provide is appreciated.
It looks like you add teamObjDetails AFTER saving it with newTeam.save().then( ... )
I'm not a lot familiar with Mongoose but I don't see how could the team details could be present if not added before saving.
Let me know if it changes something !
A. G
i was exploring Ajv with ajv-errors for validating json schema and producing custom error messages. everything works as of now but i can't set custom error message for type for individual values.
const emailSchema = {
type: 'object',
required: ['foo', 'bar', 'car'],
properties: {
foo: { type: 'integer' },
bar: { type: 'string' },
car: { type: 'string' }
},
errorMessage: {
type: 'should be an object',
required: {
foo: 'foo field is missing',
bar: 'bar field is missing',
car: 'car field is missing'
}
}
};
outputs following error
[
{
"keyword": "type",
"dataPath": "/foo",
"schemaPath": "#/properties/foo/type",
"params": {
"type": "integer"
},
"message": "should be integer"
},
{
"keyword": "errorMessage",
"dataPath": "",
"schemaPath": "#/errorMessage",
"params": {
"errors": [
{
"keyword": "required",
"dataPath": "",
"schemaPath": "#/required",
"params": {
"missingProperty": "bar"
},
"message": "should have required property 'bar'"
}
]
},
"message": "bar field is missing"
},
{
"keyword": "errorMessage",
"dataPath": "",
"schemaPath": "#/errorMessage",
"params": {
"errors": [
{
"keyword": "required",
"dataPath": "",
"schemaPath": "#/required",
"params": {
"missingProperty": "car"
},
"message": "should have required property 'car'"
}
]
},
"message": "car field is missing"
}
]
the first error object with message "should be integer", can i customize it like foo must be an Integer.
I am expecting something like below but it gives be schema error.
type : {
foo : "foo must be an Integer"
}
Thanks.
You must declare errorMessage as keyword inside each of properties, see this example:
const emailSchema = {
type: 'object',
required: ['foo', 'bar', 'car'],
properties: {
foo: {
type: 'integer',
errorMessage: {
// In here must be errorMessage not errorMessages
type: 'foo must be an Integer', // Your Custom Error Message
},
},
bar: { type: 'string' },
car: { type: 'string' },
},
errorMessages: {
// Change from errorMessage to errorMessages
type: 'should be an object',
required: {
foo: 'foo field is missing',
bar: 'bar field is missing',
car: 'car field is missing',
},
},
}
For use cases where we have some custom errorMessage or any other data, we have to use the schema path.
When we get the validation error, we also get the error.keyword in my case I had extra validation in if and else block as below
schema.allOf= Object.keys(bankCodes).map((key: any) => ({
if: {
properties: {
routingCodeType1: { const: bankCodes[key].code },
},
},
then: {
properties: {
routingCodeValue1: {
pattern: bankCodes[key].pattern, //<-- this was cause of validation fail
errorMessage: bankCodes[key].errorMessage,
},
},
},
}))
so in the error.keyword I would get pattern as well as schemaPath=/#/allOf/2/then/properties/routingCodeValue1/pattern
so basically I would have to use this schema path to fetch the related data back from schema. Following code helped me with it
const getPatternMessage = (error: any, schema: any) => {
if (error.keyword === 'pattern') {
const fieldName = error.dataPath.substring(1); // routingCodeValue1
const keyArr = error.schemaPath.split('/'); // ['#','allOf','2'..,'pattern']
keyArr.pop(); // remove '#'
keyArr.shift(); // remove 'pattern'
const prop = keyArr.reduce((acc, key) => acc[key], schema);
/**
prop contains {
pattern: '^[a-z]{9}$',
errorMessage:'routingCodeValue1 should be 9 characters'
},
*/
return {
[fieldName]: prop.errorMessage,
};
}
};
This way we are able to extract get custom errorMessage or any other data we want
Gist is to use the schemaPath property
I have a div in which I store the fields from a form that I have created in the following Javascript function:
information: function(){
var objData = $("#InformationJson").html();
var dataJSON = JSON.parse(objData);
$("#informationDialog").dialog({
autoOpen: false,
width: 520, height: 470,
close: function() {
$("#informationForm").validate().resetForm();
$("#informationForm").find(".error").removeClass("error");
}
});
$.validator.addMethod("regx", function(value, element, regexpr) {
return regexpr.test(value);
}, "");
$("#informationForm").validate({
rules: {
name: {
required: true,
regx: /^([Α-Ωα-ωa-zA-Z0-9_]+)$/
},
displayed_name: { required: true},
mode: { required: true},
process_group: { required: false},
process_admin: { required: false},
process_in_force_from: { required: false},
process_in_force_to: { required: false},
created: { required: false},
website: { required: false},
version: {
required: true,
regx: /^-?\d\d*$/
},
description: { required: false},
},
messages: {
name: "Field should include characters and/or underscore(s)",
displayed_name: "",
mode: "",
process_group: "",
process_admin: "Please select the Process Admin",
process_in_force_from: "Please fill in the day from which the Process will be in force",
process_in_force_to: "Please fill in the day to which the Process will be in force",
website: "Please fill in the website",
created: "Please fill in the date at which the Process was created ",
version: "Field should include non-negative integers",
description: "Please fill in the Process Description",
},
submitHandler: function() {
formSubmitHandler();
}
});
var formSubmitHandler = $.noop;
var showInformationDialog = function(client) {
if(client){
$("#name").val(client.name);
$("#displayed_name").val(client.displayed_name);
$("#mode").val(client.mode);
$("#process_group").val(client.process_group);
$("#process_admin").val(client.process_admin);
$("#process_in_force_from").val(client.process_in_force_from);
$("#process_in_force_to").val(client.process_in_force_to);
$("#website").val(client.website);
$("#created").val(client.created);
$("#version").val(client.version);
$("#description").val(client.description);
}
else{
$("#name").val('');
$("#displayed_name").val('');
$("#mode").val('');
$("#process_group").val('');
$("#process_admin").val('');
$("#process_in_force_from").val('');
$("#process_in_force_to").val('');
$("#website").val('');
$("#created").val('');
$("#version").val(["1"]);
$("#description").val('');
}
formSubmitHandler = function() {
saveClient(client);
};
$("#informationDialog").dialog("option", "title", "Process")
.dialog("open");
};
var saveClient = function(client) {
$.extend(client, {
name: $("#name").val(),
displayed_name: $("#displayed_name").val(),
mode: parseInt($("#mode").val(), 10),
process_group: parseInt($("#process_group").val(), 10),
process_admin: parseInt($("#process_admin").val(), 10),
process_in_force_from: $("#process_in_force_from").val(),
process_in_force_to: $("#process_in_force_to").val(),
website: $("#website").val(),
created: $("#created").val(),
version: $("#version").val(),
description: $("#description").val(),
});
var myhtml = {
"name": $("#name").val(),
"displayed_name": $("#displayed_name").val(),
"mode": $("#mode").val(),
"process_group": $("#process_group").val(),
"process_admin": $("#process_admin").val(),
"process_in_force_from": $("#process_in_force_from").val(),
"process_in_force_to": $("#process_in_force_to").val(),
"created": $("#created").val(),
"website": $("#website").val(),
"version": $("#version").val(),
"description": $("#description").val() };
$("#InformationJson").html(JSON.stringify(myhtml));
$("#informationDialog").dialog("close");
};
showInformationDialog(dataJSON);
},
and I save them as a json string with the following code:
var InformationJson = document.getElementById('InformationJson').textContent;
var jsonString = JSON.stringify(InformationJson);
But the JSON string I get is the following:
"{\"name\":\"test\",\"displayed_name\":\"test\",\"mode\":\"1\",\"process_group\":\"2\",\"process_admin\":\"2\",\"process_in_force_from\":\"2017-01-05\",\"process_in_force_to\":\"2017-01-19\",\"created\":\"2017-01-26\",\"website\":\"test\",\"version\":\"3\",\"description\":\"test\"}"
How can I get it as a regular JSON object i.e :
{"name":"test","displayed_name":"test","mode": 1 ,....,"description":"test"}
Where am I wrong?
The jsonString variable holds a string that represents a javascript object. This is the format that you get when you stringify an object. The format you want to get is an object and you get it like this:
var object = JSON.parse(jsonString);
Check the following example
var jsonString = "{\"name\":\"test\",\"displayed_name\":\"test\",\"mode\":\"1\",\"process_group\":\"2\",\"process_admin\":\"2\",\"process_in_force_from\":\"2017-01-05\",\"process_in_force_to\":\"2017-01-19\",\"created\":\"2017-01-26\",\"website\":\"test\",\"version\":\"3\",\"description\":\"test\"}";
$('#getObject').click(function() {
var obj = JSON.parse(jsonString);
console.log(obj);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<p>Check the console for the output!!!</p>
<button id="getObject" type="button">Get Object</button>
When you use .textContent you are just getting the text from your div, not the JSON that you are expecting. You can use JSON.parse(jsonString) to get your data as an object as you expext.
That's the escaped JSON-string you're getting - which is correct and what JSON.stringify does.
To get the JSON-object back you can use JSON.parse:
JSON.parse(jsonString)