How to split up Postgres data into JSON/object, or an easily usable format for Express - postgresql

I'm using pg-promise to facilitate requests between Express and a Postgres database.
Using pg-promise's any:
db.any('select * from blog')
.then(function (data) {
console.log(data);
})
.catch(function (error) {
console.log('ERROR:', error);
});
There is only one row in the Postgres table, so the query above gets a block of data from Postgres that, when output to the terminal, looks like this:
[ { id: 1,
date: '2018-12-17',
title: 'Here is a Title',
article: "Okay, there's not much here yet.",
img1: null,
img2: null,
img3: null,
keywords: 'news' } ]
In an effort to break up this data into usable bits that I can then assign to values in Express, I attempted to use JSON.parse() on this data. I really didn't know what to expect from doing this.
db.any('select * from blog')
.then(function (data) {
data = JSON.parse(data); // attempting to parse the Postgres data
console.log(data);
})
An error occurred:
ERROR: SyntaxError: Unexpected token o in JSON at position 1
I also tried to call on this data as if it were an object.
db.any('select * from blog')
.then(function (data) {
console.log(data);
console.log(data.id); // attempting to get just the id from the data
})
Which output to the terminal as:
undefined
How can I use this data within a js environment like Express? Not sure if it makes a difference, but I'm trying to use Pug to template everything to the front-end.

The select query returns array of objects with each element in the array corresponding to a row in the table (blog) in your case and each key in the object corresponding to the table column.
I am not sure why you are trying to JSON-parse it, as JSON expects an object, and it cannot parse arrays.

Try JSON.parse(JSON.stringify(data));

Related

Unknown bson type DECIMAL128 in when show on template client?

I user find for meteor and aggregate I try to get data form server I test both of them it work but, I get trouble when I use
.toNumber() function with aggregate that data type amount is Decimal in mongodb. I am not sure to get data to show on client in template. any suggestion Please help me
My Code collection Schema
Collection schema (SimpleSchema)
amount: {
type: Object, // I tried use `Decimal`
blackbox: true,
},
Method on server sample it work find after insert amount store in data type Decimal and get data both with findOne abd aggregate
import { Decimal } from 'meteor/mongo-decimal'
Meteor.methods({
insert(){
return Collection.insert({amount: Decimal(0.123)})
},
findOne(){
return Collection.findOne({})
},
aggregate(){
return Collection.aggregate([{ $limit: 1 }])[0] // sakulstra:aggregate
}
})
Get data in Client when get with findOne .toNumber() it work fine but when I use with aggregate .toNumber() it unknown.
So during find query I am getting Unknown bson type DECIMAL128
Meteor.call('findOne', (err, res)=>{
res.amount.toNumber() // Work fine with Decimal JS method
})
Meteor.call('aggregate', (err, res)=>{
res.amount.toNumber() // don't work with Decimal JS method
})

Accessing OData model through read operation

adminloginButton: function (oEvent) {
var model1 = new sap.ui.model.odata.ODataModel("TEST");
sap.ui.getCore().setModel(model1);
model1.read("/admin(ADMINID,ADMINNAME,ADMINPASSWORD)", {
success: function (oData, oResponse) {
},
error: function (err) {
}
});
}
Here what to write in the success function to read a particular row from the table admin having three columns ADMINID,ADMINNAME & ADMINPASSWORD (ALL THREE ARE KEYS) and then to message toast the values in rows.
If you use oData from sap Netweaver (what i think you want to do) and you have implemented the method for GET_ENTITY returning the structure than contain the row with your ids than you must simply use MessageToast.show(oData.SPECIFIC_COLUMN)
I hope it helps.

SequelizeJS: How to know success or failure when executing an INSERT raw query?

I use PosgreSQL. Now I have an INSERT raw query. I want to know ask 2 questions:
I want to know if it is success or failure when executing it
If success, I want to get the new data I inserted
var querydb = INSERT INTO chat_message VALUES (DEFAULT, '${text}',
'${created_at}', '${room_id}', '${user_id}');
sequelize.query(querydb, { type: sequelize.QueryTypes.INSERT})
.then(insertID => {
resolve(insertID)
})
.catch(err => {
reject(err)
})
First of all you shouldn't be using raw queries until unless you are not able to do anything with sequelize.js , or else there is no use of using this library.
Use sequelize.js as much as possible , so that you can use default functionality very easily.
So this is how you can do the same thing in sequelize.js way :
ChatMessage.create({
text: text,
room_id: room_id,
user_id: user_id
created_at: new Date() // Not required , it will be auto managed by sequlize
}).then(message => {
console.log(message);
// you can now access the newly ChatMessage task via the variable message
}).catch(err => {
// catch error if anything goes wrong
})

TypeError: Cannot read property '_id' of undefined at insertDocuments at insertOne

I was trying to insert a record into a collection when this error was thrown. I went through the mongodb doc on insertOne and I understand that mongod will automatically add the _id when it is not specified as in my case, so I'm wondering why there is an undefined id error.
Here's the code I'm working with, first the api route and the data I'm trying to insert
app.post('/api/contacts', (req, res) => {
// retrieve the user being added in the body of the request
const user = req.body;
// obtain a reference to the contacts collection
const contactsCollection = database.collection('contacts');
// insert data into the collection
contactsCollection.insertOne(user, (err, r) => {
if (err) {
return res.status(500).json({error: 'Error inserting new record.'});
}
const newRecord = r.ops[0];
return res.status(201).json(newRecord);
});
});
The json data for inserting
{
"name": "Wes Harris",
"address": "289 Porter Crossing, Silver Spring, MD 20918",
"phone": "(862) 149-8084",
"photoUrl": "/profiles/wes-harris.jpg"
}
Database connection to the to the database hosted on mlab is successful with no errors. What could possibly be wrong here and how do I go about fixing this error?
The error message means that the object that you are passing into insertOne is undefined (and hence it can’t read the _id property of of it). You might like to look at what exactly req.body contains as that is what is passed as user. (I don’t know TypeScript but, in node/express, I have had errors like this when I didn’t set up bodyParser correctly)
Faced a similar problem. Solved and it by using body-parser and then parsing the json object being sent as follows:
const bodyParser = require('body-parser');
app.use(bodyParser.json());
// parse application/json
app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
})

In mongo how to get the current position of the record in the table with the total records for pagination?

I'm trying to return create a paginated list. I used graphql to query the data. With my query, I pass the number of records I need (In a variable named first) and the ID of the last fetched record (In a varible called after). Now I managed to write a query (Note that I used mongoose) to fetch the records. Now what I need to do is get the relavant information to perform the pagination like hasNextPage, hasPreviousPage, currentPage and totalPages.
To get most of these information I need to get the total number of records in the database. To do that I need to send another db request.
I also need to know the position of the record in the table. No idea how.
Here's the query:
new Promise((resolve, reject) =>
Company.where('_id')
.gt(after)
.limit(first)
.lean()
.exec((error, doc) => {
if (error) {
reject(error);
}
resolve({
edges: doc,
pageInfo: {
hasNextPage: '...',
hasPreviousPage: '...',
currentPage: '...',
totalPages: '...'
}
});
}))
Any idea how to do this efficiently?
you can try this module mongoose-paginate
here what i uses, for pagination,
var current = req.query.filter.current;
var limit = req.query.filter.limit;
console.log('params.query.filter.current',current);
var skip = Number(limit)*Number(current)-Number(limit);
console.log('skip::',skip);
Cours.find({'attributes.version.status': true}).skip(skip).limit(limit).sort({_id:'asc'}).exec(function (err, resulta) {
if (err) {
console.log('erreur trouverCours');
res.json({
protecteds: err
});
}
console.log('cours ::', resulta);
res.json({
"data": resulta
});
});