Create JSON using for loop, Express.js - json

I'm newbie to express.js. I want to create a JSON using for loop. But the code returns object object. I don't know why. But for a single JSON, it returns as a JSON value. In this code, I have added a function to retrieve my JSON values from mongoDB. Please help me to complete this.
router.get('/', (req, res) => {
Followups.find({}).then(followupData => {
Staffs.find({}).then(staffData => {
Institutions.find({}).then(institutionData => {
var fcount = Object.keys(followupData).length;
var scount = Object.keys(staffData).length;
var icount = Object.keys(institutionData).length;
console.log(icount);
var jsonData = '';
function getStaffData(id) {
return staffData.filter(
function(staffData) {
return staffData._id == id;
}
);
}
function getInstitutionData(id) {
return institutionData.filter(
function(institutionData) {
return institutionData._id == id;
}
);
}
for (i=0; i<fcount; i++)
{
fstaffid = followupData[i].staffid;
fschoolid = followupData[i].schoolid;
staffDetails = getStaffData(fstaffid);
institutionDetails = getInstitutionData(fschoolid);
jsonData += {
staffname : staffDetails[0].achternaam + ' ' + staffDetails[0].voornaam + ' ' + staffDetails[0].tv,
staffplace : staffDetails[0].plaats,
staffphone : staffDetails[0].telefoon,
schoolname : institutionDetails[0].instellingsnaam,
schoolplace : institutionDetails[0].plaatsnaam,
schoolphone : institutionDetails[0].telefoonnummer,
notes : followupData[i].notes,
date : followupData[i].date,
created_at : followupData[i].created_at,
status : followupData[i].seen
}
}
console.log(jsonData);
res.render('followup', {followupData:followupData, jsonData: jsonData});
});
});
});
});

Problem solved by using concat
jsonData = jsonData.concat({
followupid : followupData[i]._id,
schoolid : followupData[i].schoolid,
staffid : followupData[i].staffid,
staffname : staffDetails[0].achternaam + ' ' + staffDetails[0].voornaam + ' ' + staffDetails[0].tv,
staffplace : staffDetails[0].plaats,
staffphone : staffDetails[0].telefoon,
schoolname : institutionDetails[0].instellingsnaam,
schoolplace : institutionDetails[0].plaatsnaam,
schoolphone : institutionDetails[0].telefoonnummer,
notes : followupData[i].notes,
date : followupData[i].date,
created_at : followupData[i].created_at,
status : followupData[i].seen
});

You can display the data of jsonData like:
console.log(JSON.stringify(jsonData));
object object means jsonData is a JSON object, you cannot display a JSON object directly. You must stringify it before doing this.
You may be able to find more about the issue after using JSON.stringify

Related

Wrong string format when i use persian and english together in Node Js

I have a node js project with MySql database. I have to use Persian data in my DB like:
UserModel = {id: 1200, firstName: 'صابر', lastName: 'سجادی' , nationalCode:'4640147800', displayName: 'saber-sajadi', status: 1, createDateTime: null };
so for run stored procedure i need to convert object to string with this Code:
let objectToString = (object) => {
let _string = "";
let i = 1;
for (let key in object) {
var val = object[key];
_string += (val == undefined || val == null) ? `null` : `'` + val + `' `;
if (i < Object.keys(object).length) {
_string += " , ";
i++;
}
}
return _string;
}
I expect the output of the function to be as follows:
but it return:
1200,'صابر','سجادی','4640147800','saber-sajadi','1',''
Please help me to solve this problem
we can use this function to solve problem:
function wrap(str){ return '\u202B' + str + '\u202C'; }

How can I solve this problem : getting values, and type error

I want to get values like '2'. But Board.findOne({attributes: ['deadline']}, {where : {name : boardID}}) print 'id : 2'. I want to solve this.
Moreover, I have a TYPEERROR like this.
TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Sequelize'
| property 'dialect' -> object with constructor 'MysqlDialect'
--- property 'sequelize' closes the circle
How can I solve this problems?
router.post('/create/:boardID', async (req,res,next) => {
const boardID = req.params.boardID;
try{
const find = await Board.findOne({attributes: ['deadline']}, {where : {name : boardID}});
const deadline = moment(find).format();
if(moment(deadline).diff(moment().format()) < 0){
const post = await Post.create({
content : req.body.content,
url : req.body.url
});
res.json(Object.values(find));
const submit = await Submit.create({
userId : req.body.userId,
boardId : Object.values(find)
});
res.json(post + " : " + submit);
} else {
return res.json({req : false, msg : '기간이 지났습니다'});
}
} catch (err) {
console.error(err);
next(err);
}
});
I think that, you have been wrong when using findOne
const find = await Board.findOne({
attributes: ['deadline'],
where : {name : boardID}
});
const deadline = moment(find.deadline).format();
You could use to try this.

JSON to OData String for Query

How can I turn a JSON object, i.e. { username: "john", password: "1234" } into an OData string query in a function using typescript? I could not find a library to do this for me (Angular 6). Here is my attempt:
function ConvertToODataString (json: Object) {
let ret_str: string = "";
for (let key in json) {
ret_str += (key + "=" + json[key] + "&");
}
if (ret_str) {
ret_str = ret_str.substr(0, ret_str.length - 1); // remove last &
}
return ret_str;
}
Does anyone know of a better way? For now, my json is not multi-leveled.
You can use for ... in to enumerate the object properties, adding each key/value pair to an array, and combine the values with Array.join:
function convertObjectToQuery(obj: Object): string {
let values = new Array<string>();
for (let prop in obj) {
values.push(`${prop} eq '${obj[prop]}'`);
}
return encodeURI("$filter=" + values.join(" and "));
}
See this stackblitz for a demo.
JSON.parse function.
Example:
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
json={ "name":"John", "age":30, "city":"New York"};
var obj = JSON.parse(json+'');
I decided to use the HttpParms module instead:
import { HttpParams } from "#angular/common/http";
const params = new HttpParams()
.set("$filter", "Username eq '" + parameters["Username"] + "' and Password eq '" + parameters["Password"] + "'")
.set("$count", "true");
console.log(params.toString());

Angular - TypeError: Converting circular structure to JSON

I'm getting this error at angular service's map method but my returned datas doesn't seem to contain any circular reference, here is my json object:
[{"id":14,
"sender":
{"id":20,"email":"p.martelliere#gmail.com","username":"test5","roles":
["ROLE_USER"],"status":"active","note":"0","points":0,
"devices":[],"job":"Caisse","showJob":false,"notificationsActivated":true,
"connected":true,"tokenConfirm":"","birthDate":[]
},"receiver":
{"id":12,"email":"test2#yopmail.com","username":"test2","tokenConfirm":"",
"job":"g\u00e9rant","showJob":false,"note":"0","points":0,
"roles":["ROLE_USER"],"status":"active","notificationsActivated":true,
"connected":true,"devices":[]
},
"myNeed":"Te ster",
"whatICanGive":"1",
"messages":[],
"status":"active"
}]
Here's my chatRequest angular Entity:
export class NmChatRequest {
// Raw attributes
id : number;
myNeed : string;
whatICanGive : string;
status : string;
createdAt : Date;
updatedAt : Date;
deletedAt : Date;
// x-to-one
id_receiver: number;
constructor(json? : any) {
if (json != null) {
this.id = json.id;
this.myNeed = json.myNeed;
this.whatICanGive = json.whatICanGive;
this.status = json.status;
this.id_receiver = json.id_receiver;
if (json.createdAt != null) {
this.createdAt = new Date(json.createdAt);
}
if (json.updatedAt != null) {
this.updatedAt = new Date(json.updatedAt);
}
if (json.deletedAt != null) {
this.deletedAt = new Date(json.deletedAt);
}
}
}
}
This entity is used to get the object from json.
Here's my ChatRequestService:
/**
* Create the passed nmChatRequest.
*/
add(nmChatRequest : NmChatRequest, token: string) : Observable<NmChatRequest> {
let body = nmChatRequest;
return this.http.post(this.chatUrl, body, {headers: new HttpHeaders({ 'Content-Type': 'application/json', 'X-Auth-Token': token })})
.pipe(
map(response => new NmChatRequest(response)),
catchError(this.handleError)
);
}
What am I missing ?
Thanks to anyone who will take the time to read/answer this question.
I built a stackblitz from the above provided pieces. It seemed to work fine for me if I changed the json string to an object instead of an array.
So no outside brackets:
{"id":14,
"sender":
{"id":20,"email":"p.martelliere#gmail.com","username":"test5","roles":
["ROLE_USER"],"status":"active","note":"0","points":0,
"devices":[],"job":"Caisse","showJob":false,"notificationsActivated":true,
"connected":true,"tokenConfirm":"","birthDate":[]
},"receiver":
{"id":12,"email":"test2#yopmail.com","username":"test2","tokenConfirm":"",
"job":"g\u00e9rant","showJob":false,"note":"0","points":0,
"roles":["ROLE_USER"],"status":"active","notificationsActivated":true,
"connected":true,"devices":[]
},
"myNeed":"Te ster",
"whatICanGive":"1",
"messages":[],
"status":"active"
}
If you are indeed getting an array and not a single object, you may need to modify your code to pass in the first element of the array. Something like this:
map(response => new NmChatRequest(response[0]))
Here is the stackblitz: https://stackblitz.com/edit/angular-wgunjb?file=src%2Fapp%2Fapp.component.ts

How to query in mongodb programmatically?

I wannt to create code like this:
var result = Attributes.find({
attribute_name : {
$exist : true,
$in : [1]
}
});
but programmatically, so i ceate code like this:
var genQuery = '{ "' + by + '" : { "$exists" : true, "$in" : [' + data + ']} }';
var result = Attributes.find(genQuery);
but I get error maximum call stack
because result of JSON.parse(genQuery)
{ _id: { '$exists': true, '$in': [ 1 ] } }
How to query in mongodb programmatically?
Your genQuery variable you declare is a String, but you cannot pass strings as selectors or modifiers in find() functions.
You should create an Object to make it works:
var genQuery = {};
//use this notation to declare a new object key depending on a variable
genQuery[by] = {
$exists: true,
$in: [1]
};
var result = Attributes.find(genQuery);