How to send and handle a json file in javascript - javascript

on serverside, i get a simple json file via REST with a lot of IDs, something like that:
[ {
"_id": "5825a49dasdasdasd8417c1b6d5",
}
"_id": "dfsdfsdf4960932218417c1b6d5",
}
"_id": "23434344960932218417c1b6d5",
},]
For that i have written in the main:
main.post('/..../add', Controller.addEvent);
In the Controller, i want to recieve the request and search in the mongodb for these ID's, because i need some informations about these IDs
exports.addEvent = function(req, res) {
var collection = db.get().collection('events');
My question is, if someone send me over "localhost:8080/events/add" the given simple json file, how do i have to handle this json? i need the ID's and want to search with them.
Thanks for help!
----------ADDED------------
I am bit further now. In my controller i have the following function
exports.addevent = function(req, res)
{
var ids = req.body;
console.log(ids);
}
Now i'm getting all IDs, which i have posted with "Postman" from chrome.
The output in the console is:
[ { _id: '5825a49dasdasdasd8417c1b6d5' },
{ _id: 'dfsdfsdf4960932218417c1b6d5' },
{ _id: '23434344960932218417c1b6d5' } ]
How can i have every single ID?

Ok, the request is an object and not a string. That was the error :-/
for(var i in ids) {
console.log(ids[i]._id);
}
and it works, now i can connect to the database and search for the id

Related

How to get a single element by its _id from an array of objects which is inside another object coming from MongoDB

I created a Mongoose schema that allowed me to save a whole JSON object which contains an array of objects (those objects have the _ids I want), but when I try to get one user from router.get express (I'm using findById), it returns null, when I do a get petition getting the whole data (using find() method) it looks like this:
thanks to all of you, English is not my first language, sorry for whatever grammar mistake that I could've made
[
{
"_id": "6384db62827c2f0816944734",
"arrayData": [
{
"description": "KEYCAPS",
"price": "$99.00",
"img": "link,of.the.image",
"_id": "6384db62827c2f0816944735"
},
{
"description": "KEYCAPS",
"price": "$99.00",
"img": "link,of.the.image2",
"_id": "7454db62827c2f0816912345"
}
]
}
]
I've tried other ways of getting the ids, to be honest I've been coding just for a couple of months, I'm a little shy of showing it but I believe this is the code I need to change
router.get('/users/:id', (req, res) => {
const { id } = req.params;
userSchema
.findById(id)
.then((data) => {res.json(data)})
.catch((err) => res.json({message: err}))
})
by the way my request.http enter image description here
enter image description here

Express js with mysql update only fields that are passed

I've been trying to setup a rest API for a few days now. I've been following a great tutorial that really helped me understand a large part of how these work (sending requests, getting responses, etc). However it uses MongoDB and Mongoose. I'm using MySQL. My tables and views are a bit complicated so I decided instead of using an ORM I'd just use mysql2 package and do the querying myself. I'm stuck with trying to PATCH and PUT at the moment. Part of my front end functions by sometimes only sending 1 or 2 fields that need to be updatd (a PATCH from everything I've gathered). So I used part of the MongoDB and Mongoose tutorial to build an array of objects and pass them into connection.query. Here's my patch route:
router.patch('/:txnid', (req, res, next) => { //UPDATE fields that are passed
const txnid = req.params.txnid;
for (const field of req.body) {
fieldsToUpdate[field.name] = field.value;
}
connection.query("UPDATE QuoteToClose SET ? WHERE qb_TxnID = '" + txnid + "'", { fieldsToUpdate }, function (error, results) {
if (error) {
res.status(404).json({
message: error,
field: fieldsToUpdate
});
} else {
res.status(201).json({
"record_count" : results.length,
"error": null,
"response": results
});
}
});
});
Sometimes I will pass 1 field, sometimes I will pass 2. In this case I'm only passing 1. I build my body in POSTMAN and send this with the PATCH request:
[
{
"name": "margin",
"value": "50"
}
]
When I run this through POSTMAN I get the error:
{
"message": {
"code": "ER_BAD_FIELD_ERROR",
"errno": 1054,
"sqlState": "42S22",
"sqlMessage": "Unknown column 'fieldsToUpdate' in 'field list'"
},
"field": {
"margin": "50"
}
}
I'm not sure why though. I'm not using Mongoose unfortunately so I don't know if something is dependent on it that I'm missing. My body parser is set like this:
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
I want to dynamically build that query instead of specifying each field (it just seems cleaner this way.
Hi im using this library build dynamic queries.https://www.npmjs.com/package/flexqp
let result = await qp.executeUpdatePromise('update user set ? where user.id = ?', [user, user.id], dbconfig);
user is an object with lots of sub elements, the library will auto populate the
query to E.g update user set name = 'xxx' , address ='xxx' ..etc where user.id = 1
fieldsToUpdate is already an object. If you remove the curlies when you parameterize if you should be good to go:
connection.query("UPDATE QuoteToClose SET ? WHERE qb_TxnID = '" + txnid + "'", fieldsToUpdate,
Also, as a side note that string concatenation is a bad idea, you're just asking for a SQL Injection attack.

How to select a JSON object from Firebase Database?

I have a Firebase structure like below. I want to get the message as a returned object. To do this in SQL like
select messages from HukMesssage
How can I do that?
Can anyone helps me how to change the SQL to Firebase query?
My json file looks like below
{
"HukMessages":
[
{
"To": 1,
"From": 2,
"messages": [
{
"name": "'Venkman'",
"message": "'You on your way?'",
"face": "'img/venkman.jpg'"
},
{
"name": "'Felix He'",
"message": "'Ionic comes with a set of colors to start with, but as a general rule colors are meant to be overridden. '",
"face": "'img/felix.jpg'"
}
]
}
]
}
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
Your code will need to deal with the list. Something like:
var query = firebase.database().ref().child("HukMessages").orderByChild(‌​"From").equalTo('2')‌​;
query.once("value", function(snapshot) {
console.log(snapshot.key); // this will print HukMessages, because that's the location you queried
snapshot.forEach(function(child) {
console.log(child.key); // this will print the key of a message
});
});

Dynamic html form generation in MEAN stack

I've just started learning on MEAN stack and need to generate dynamic forms on the fly.
The requirement is to import document (excel/csv/xml/xls etc..) and generate dynamic forms using it so a user can update their data and again export it into the respective file.
So to accomplish this I'm converting documents to JSON format and storing JSON data into the MongoDB database.
Ex: Consider this xlsx data:
ID Name dob Gender
1 user1 7-Dec-87 m
2 user2 8-Dec-87 f
3 user3 9-Dec-87 f
3 user4 4-Dec-87 m
And I'm converting this using xlsx-to-json module to JSON format and storing it into Mongodb.
app.post('/myapp', function (req, res) {
//console.log("===========" + req.file.path);
converter({
input: req.file.path,
output: "output.json"
}, function (err, result) {
if (err) {
console.error(err);
} else {
console.log(result);
db.collection('test').insert(result, function (err, doc) {
console.log(err);
res.json(doc);
});
}
});
});
Here I'm fetching above data from Mongodb & express.js
app.get('/myapp', function (req, res) {
db.collection('test').find(function (err, docs) {
console.log(docs);
res.json(docs);
});
});
app.get('/birthdaylist/:id', function (req, res) {
var id = req.params.id;
console.log(id);
db.collection('test').findOne({_id: mongojs.ObjectId(id)}, function (err, doc) {
console.log(JSON.stringify(doc));
res.json(doc);
});
});
and here's the JSON output:
[
{ dob: '7-Dec-87', ID: '1', Name: 'user1' },
{ dob: '8-Dec-87', ID: '2', Name: 'user2' },
{ dob: '9-Dec-87', ID: '3', Name: 'user3' },
{ dob: '4-Dec-87', ID: '4', Name: 'user4' }
]
So, I've few queries:
Is this the correct approach I'm doing to generate dynamic form from xlsx/csv..etc ? If yes, then how can I generate dynamic form from above JSON.
While exploring on google I've found mongodb generates form automatically (https://github.com/GothAck/forms-mongoose)
So will it help because there may be chance of huge data on excel files.
Any help would be really appreciated.
Do you actually need to analyze an arbitrary spreadsheet and dynamically extract the schema, or do you know the schema ahead of time? If you know the schema, then the Mongoose form generating example is straightforward. But make sure that is actually a requirement because it is tough.
You are never going to be 100% because spreadsheets are created by users and users do weird things. But you can make something that works most of the time.
You need something that takes a JSON object and extracts the schema and puts that in a Mongoose schema format.
So you want to add an interesting module to Mongoose schema. I searched node-modules.com and this came up: https://github.com/Nijikokun/generate-schema
Form generation is not a trivial task. You may want to consider using a library for this. Here are a few that might be useful to you:
http://schemaform.io/
https://github.com/jdorn/json-editor/
Also, if you need help generating JSON schema from JSON:
http://jsonschema.net/#/
and of course: http://json-schema.org/

MongoDB / MongoLab Remove request works locally but deletes database when live

The following is using nodejs, expressjs, mongodb. On the live site it is using mongolab. I am making a POST request from the front end to the server, and the server handles the request by deleting a single matching record from the database. The server work (done in ExpressJS is as follows:
var removeStuff = req.body.removeStuff;
var currentId = req.user._id;
var currentEmail = req.user.email;
myStuff.findOne({
$and: [
{ $or: [{stuff: removeStuff}] },
{ $or: [{apid:currentId},{apiemail:currentEmail}] }
]
}, function (err, currentStuff) {
currentStuff.remove();
res.send('Stuff was removed from database...')
});
What's really strange is that this works perfectly for the site when I'm running it on localhost. But when it's live, making the request removes ALL records from the database.
Ok, I got it. I'm not sure exactly why the original doesn't work, but I found that in this StackOverflow question someone answered a similar question. What they did was along the lines of:
var removeStuff = req.body.removeStuff;
var currentId = req.user._id;
var currentEmail = req.user.email;
myStuff.findOneAndRemove({
$and: [
{ $or: [{stuff: removeStuff}] },
{ $or: [{apid:currentId},{apiemail:currentEmail}] }
]
}, function (err) {
res.status(200).send("it worked...");
});

Categories