Wrong JSON format after JSON stringify in Javascript - javascript

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)

Related

Converted string to json, how to get the label and data?

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]);
}

How to insert ref objectId in nodejs?

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();

use mongooseModel.find() on schema that has a Schema.Types.Mixed property

I have trouble using postModel.find() query in a schema that defined as Schema.Types.Mixed.
this is a sample of my schema
const PostSchema = new mongoose.Schema({
//.....
address: {
type: String,
required: true,
},
postDetails: {
type: Schema.Types.Mixed,
required: true,
},
author: {
type: Schema.Types.ObjectId,
ref: 'User',
},
//.....
});
this is a sample document stored in db
{
//.....
"state": "Lakes State",
"address": "some address",
"postDetails": {
"type": "Cages",
"condition": "Used"
},
//......
}
it is giving me an empty array if I use this
const queryObject = {
postDetails: {
type: 'Cages',
},
};
return this.postModel.find(queryObject);
but it gives the desired results if I include all the properties like this
const queryObject = {
postDetails: {
type: 'Cages',
condition: 'Used',
},
};
return this.postModel.find(queryObject);
How do i get all matching posts that have postDetails.type = 'Cages' ? without knowing all available properties inside postDetails
there are some similar questions about this here. but most of them are using arrays instead of an object
You can use dot notation for querying embedded documents
postModel.find({
"postDetails.type": "Cages"
});

How to validate Array of Objects in Mongoose

I need to validate the array of objects in my schema
Schema:
user: [{
name: String,
Age: String,
Contact: Number
}]
How to validate name, age and contact.
I assume your user array is inside another schema.
Let's say we have a Course model with users like this:
const mongoose = require("mongoose");
const courseSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
users: [
{
name: { type: String, required: [true, "Name is required"] },
age: { type: Number, required: [true, "Age is required"] },
contact: { type: Number, required: [true, "Contact is required"] }
}
]
});
const Course = mongoose.model("Post", courseSchema);
module.exports = Course;
To validate this in a post route you can use mongoose model validateSync method:
const Course = require("../models/course");
router.post("/course", async (req, res) => {
const { name, users } = req.body;
const course = new Course({ name, users });
const validationErrors = course.validateSync();
if (validationErrors) {
res.status(400).send(validationErrors.message);
} else {
const result = await course.save();
res.send(result);
}
});
When we send a requset body without required fields like age and contact:
(you can also transform validationErrors.errors for more useful error messages.)
{
"name": "course 1",
"users": [{"name": "name 1"}, {"name": "name 2", "age": 22, "contact": 2222}]
}
The result will be like this:
Post validation failed: users.0.contact: Contact is required, users.0.age: Age is required
It will be similar to the usual validation but inside an array, you need to make a validator function as so:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//the custom validation that will get applied to the features attribute.
var notEmpty = function(features){
if(features.length === 0){return false}
else {return true};
}
var CarSchema = new Schema({
name: {
type: String,
required: true,
},
features: [{
type: Schema.ObjectId,
ref: Feature
required: true; //this will prevent a Car model from being saved without a features array.
validate: [notEmpty, 'Please add at least one feature in the features array'] //this adds custom validation through the function check of notEmpty.
}]
});
var FeatureSchema = new Schema({
name: {
type: String,
required: true //this will prevent a Feature model from being saved without a name attribute.
}
});
mongoose.model('Car', CarSchema);
mongoose.model('Feature', FeatureSchema);
By using type key/property:
var breakfastSchema = new Schema({
eggs: {
type: Number,
min: [6, 'Too few eggs'],
max: 12
},
bacon: {
type: Number,
required: [true, 'Why no bacon?']
},
drink: {
type: String,
enum: ['Coffee', 'Tea'],
required: function() {
return this.bacon > 3;
}
}
});

Information isn't being passed to an array via Mongoose, can't work out why

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

Categories

Resources