Mongo Returns data with \n - javascript

I am using a form builder(https://github.com/kevinchappell/formBuilder). I have been able to store the generated JSON data(note that i am not sure if the data produced is in JSON form I am just storing it in a JS var) into my MongoDB. Here is where the data is coming from:
document.getElementById('getJSON').addEventListener('click', function() {
var ans = formBuilder.actions.getData('json', true);
$.ajax({
type: "POST",
dataType: "json",
data: ans,
url: "/j",
success: function(){
console.log('success');
}
});
document.forms["myForm"].submit();
});
It is generated here and sent as an AJAX call to the node server. The server then does the follows:
mongo.connect(url, function (err, db) {
assert.equal(null, err);
db.collection('clauses').insertOne(req.session.fdata, function (err, result) {
console.log('New Clause Added');
db.close();
});
});
It appears like so in the command prompt
the standard JSON format in which data appears in MongoDB
However when i fetch this data it comes as such:
[ { _id: 596de520ef77eb2614cd1e47,
'[\n\t{\n\t\t"type": "number",\n\t\t"label": "Number",\n\t\t"description":
"total number",\n\t\t"placeholder": "0",\n\t\t"className": "form-
control",\n\t\t"name": "number-1500374279764"\n\t}\n]': '' },
{ _id: 596de520ef77eb2614cd1e48 } ]
Am I passing the data in the wrong form? Or is the inserted data not in JSON in the first place? I am new to working with JSON and NOSQL databases.

Related

Insert record in mongoDB then update it - Node.Js

I am new to nodeJS and MongoDB
I want to add a record to the database on the javascript event of PageLoad, then during the visit of the user i add values to this object and then update it in the collection depending on an ID i assigned to this record. I am doing it like the following:
Front-end :
document.addEventListener('DOMContentLoaded', async() => {
var ID = function () {
return '_' + Math.random().toString(36).substr(2, 9);
};
jsLibrary.generateObject().then((objectName) => {
objectName.pageLoadTimeStamp = + new Date();
objectName.identifier = ID;
$.ajax({
type:'POST',
url:'/add',
data:JSON.stringify(objectName),
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
window.onpagehide = function(){
objectName.PageHideTimeStamp = + new Date();
$.ajax({
type:'POST',
url:'/update',
data:JSON.stringify(objectName),
contentType: "application/json; charset=utf-8",
dataType: "json"
})
};
As you can see i am assigning an ID to an object i'm receiving from a library, then logging the timestamp for pageload and sending it back-end to add it to the database. Then on the event of pageHide I am saving the timestamp of the user leaving the page, and i want to update the record in the collection to re-add it depending on its ID
Back-end: My app.js file
app.post('/add', function(req, res)
{
objName = (req.body);
db.components.insert(objName, function(err,res)
{
if(err){
console.log(err); }
console.log("SUCCESS");
});
});
app.post('/update', function(req, res)
{
objName = (req.body);
db.components.update( { identifier: objName.identifier }, objName, true )
console.log("updated");
});
I get on my console both the values SUCCESS and updated
But when i check the values in my collection; they don't seem to be updated. The pageHideTimeStamp doesn't exist.
The problem is probably with the update, I want to replace the whole record with a new one depending on the ID.
IS there a better practice? Sorry i'm new to this. Thank you
PS: its not practical for me to pass through every parameter i added to this object while updating. There are other parameters I'm adding other than PageHideTimeStamp and there could be more with time
the condition for updating should have only the check you need to apply like it should be ,
let cond = {'id' : '22'} or cond = {'name' : 'sss'} ,
you are using req.body whole object as condition you can try code like this
db.update(condition,data,this.table,function (err,refresh) {
if(err){
//console.log('err controler', refresh)
callback(err, null);
return;
}
//console.log('updated ', refresh)
callback(null,refresh);
});
Use $set for update data
db.components.update( { identifier: objName.identifier }, {$set : objName},function(err,result){
console.log('updated')
})

AJAX POST successful but does not do anything

I am building a desktop app using electron. I want to keep the list of all the recent files opened, for this I am using jquery ajax. here is my code
// this function is expected to add a file entry to my json file
this.add_recent_file = function(file_id, file_name, date_opened) {
// Execute the ajax command.
$.ajax({
type: 'POST',
url: './data/recent-files.json',
dataType: 'json',
data: {
id: file_id,
name: file_name,
date: date_opened
},
success: function() {
console.log("Success");
}
});
}
and here is my sample json file:
[
{
"id" : "1",
"name": "File.json",
"date": "24-feb-2018"
}
]
the problem is that console says 'Success' but no changes in json file. Reloading the page didn't change anything.
You can use node.js filesystem to write to the json file. check out the following code.
var fs = require('fs');
var $ = require('jquery');
this.add_recent_file = function (object) {
$.ajax({
type: 'GET',
url: './data/recent-files.json',
dataType: 'json',
success: function (files) {
// append the entry to the array.
files[files.length] = object;
// Get JSON string representation of the array.
var str = JSON.stringify(files);
// Now write it to the json file.
fs.writeFileSync(recent_file_url, str);
},
error: function () {
alert('Error updating json file.');
}
});
}
As stated by #Gerrit Luimstra, you need a backend, If you're using PHP, you might use something like this:
data/update.php
<?php
$id = $_POST['id'];
$name = $_POST['name'];
$dateX = $_POST['date'];
//update database code here
Right now you are using AJAX to POST data to a JSON file and hope that this will update the file. This however is not the case.
What you can do instead is use Electron's file system to write changes to the JSON file.
In this case, your function would become something like:
this.add_recent_file = function(file_id, file_name, date_opened) {
// Create the JSON content
var data = {
id: file_id,
name: file_name,
date: date_opened
};
// If you want to prettify the JSON content
data = JSON.stringify(data, null, 2);
// Write it to the file
fs.writeFileSync('../path/to/recent-files.json', data);
}
This however requires you to use the node filesystem package.

How to write JSON array to file in node.js and request it again client side

I'm trying to create a drag-and-drop table with save and load functionality. I'm using code from REDIPS.drag.
When using the REDIPS save function the table content is returned, client side, to the console and alert like this:
[["d2",2,2,"blue","A1"],["d1",4,5,"blue","A2"],["d3",3,2,"blue","A3"],["d4",1,4,"blue","A4"]].
I've tried a few different ways to POST the data to node and write it to file.
With this method:
script.js
$.ajax({
type: "POST",
url:"post6/json",
data: {table_content},
dataType:'json',
contentType: "application/x-www-form-urlencoded"
});
App.js
var testjson = req.body;
var tablestringify2 = JSON.stringify(testjson);
fs.writeFile('views/test.json', tablestringify2,'utf8', function (err) {
if (err) {
// append failed
} else {
// done
}
})
The data saved to file is:
{"table_content":"[[\"ns1.8b\",3,1,\"\",\"ns1.8b\"],[\"ns3.1\",4,2,\"\",\"ns3.1\"]]"}
With this method:
script.js
$.ajax({
type: "POST",
url:"post6/json",
data: table_content,
dataType:'json',
});
The data is saved to file as:
{"[":{"\"ns1.8b\",3,0,\"\",\"ns1.8b\"":{"\"ns3.1\",3,2,\"\",\"ns3.1\"":""}}}
When I use a GET, I parse the data which returns;
{ table_content: '[["ns1.8b",3,1,"","ns1.8b"],["ns3.1",5,3,"","ns3.1"]]' }
or
{[:{"ns1.8b",3,0,"","ns1.8b":{"ns3.1",3,2,"","ns3.1":""}}}
Either form cant be loaded back into the table using the REDIPS load function.
Is there any way I could get the data in the following format;
[["ns1.8b",3,0,"","ns1.8b"],["ns3.1",3,2,"","ns3.1"]]
...returned on the client side?
Or would it be possible to save it to file like that?
Perform the stringify at the client side:
$.ajax({
type: "POST",
url:"post6/json",
data: {table_content: JSON.stringify(table_content)},
dataType:'json',
});
At the server side you should be able to access req.body.table_content which will be the (JSON) string representation of the array.

Update a p element from a nodejs function

I need to send a value from a input form to a nodejs server, which triggers a calculation with this value and needs to update an p element with the result of the calculation on the client side.
How can this be done?
This is what i have:
//Server side:
app.post('/calculate/:id', function(req, res){
var title = 'Tax Calculation';
var tax= taxcalculation(req.params.id);
res.render('index', {
title: title,
tax: tax,
});
});
//Client side:
var income= document.getElementById("income");
var tax = document.getElementById("tax")
$(income).on('change', function() {
console.log("changed");
$.ajax({
type: 'POST',
url: '/calculate/'+income.value,
success: function() {
$('#tax').html('<%= tax %>');
},
error: function() { // if error occured
alert("Error occured, please try again");
},
});
});
Okay, so you don't give a lot of data, but this sounds as simple as sending a response with the results to the client side in your Node web service that does the calculations and append the result to the P element
Your server code to handle the ajax call should output a json response which will contain the content for the <p>. It should not re-render the whole index page. I don't do a lot of node.js so I'll leave that for you to figure out.
The ajax success function should accept a response as a parameter, and then operate on that response.
Assuming the server response to this ajax request is of the format {"tax": 15.99}:
$.ajax({
type: 'POST',
url: '/calculate/'+income.value,
success: function(response) {
if (response.tax || response.tax === 0) {
$('#tax').html(response.tax);
}
},
error: function() { // if error occured
alert("Error occured, please try again");
},
});

Posting an array of objects to MongoDB with Node sends empty array

I am trying to POST an array of objects to my MongoDB database using NodeJS. When I post, all my fields show up empty. I put my code below, and below that explain what each of the console.logs output. Any ideas how to sort this out?
MODEL
var mongoose = require('mongoose');
var TransferSchema = new mongoose.Schema({
uploadDate: Date,
period: Number,
transferCode: String,
voucherNumber: String,
vendor: String,
description: String,
amount: Number
});
//convert schema to model
var Transfer = mongoose.model('Transfer', TransferSchema);
//export model for use elsewhere in app
module.exports = Transfer;
AJAX
- here I've tried posting both newArray and json. Both result in the same data posted to my db, but have a different effect on the console.logs in the controller file.
console.log(newArray);
json = JSON.stringify(newArray);
console.log(json);
$.ajax({
url: "http://localhost:3000/transfers/api",
type: "POST",
data: newArray,
datatype: 'json',
success: function(data, textStatus, jqXHR) {
console.log('posted!');
},
error: function(data, textStatus, errorThrown) {
console.log('failed');
}
})
transferController.js
-when posting newArray I get the following:
body: [object Object],
Body: {"undefined": ["", "", "", etc],
Text: undefined,
Done: undefined
-when posting json I get the following:
body: [object Object],
Body: {"{\"period\":5,\"uploadDate\":2015-11-19T21:00:00.000Z\",\"transferCode\":\"1041\",\"vendor\":\"Lakes State\",\"voucherNumber\":\"0000047571\",\"description\":\"1003-1555 Sal Tax Adj Gran Sep \",\"amount\":456802}...,
Text: undefined,
Done: undefined
//Create a new transfer
function createTransfer(request, response) {
console.log('posting');
console.log('body: ' + request.body); //TEST
console.info("Body: " + JSON.stringify(request.body)); //TEST
console.info("Text: " + JSON.stringify(request.body.text)); //TEST
console.info("Done: " + JSON.stringify(request.body.done)); //TEST
var transfer = new Transfer(request.body);
transfer.save(function(error) {
// console.log('transfer and transfer: ' + transfer);
if(error) return response.json({ message: 'could not create transfer because ' + error });
response.json({ transfer: transfer });
});
}
EDIT:
I tried using Insomnia to test what I'm sending. Weirdly, the below screenshot posts on Insomnia, but does not post in my app:
Also interesting, if I post several objects in an array using Insomnia, it does not work, as seen below:
Try setting contentType: 'application/json' in your ajax request and stringify your data like so JSON.stringify(newArray). This should ensure the data you are sending up is ok.
It looks like you are sending up many transfers but then trying to create one transfer from all the data (request.body)? You would need to loop over them and create them individually. Something like this:
request.body.forEach(function(obj) {
var transfer = new Transfer(obj);
transfer.save();
});

Categories

Resources