Return model and relations newly inserted - bluebird

I have a model named Category and another one named Product.
There is a relation between the two models as is :
// Category Model
var Category = bookshelf.Model.extend({
tableName : 'categories',
hasTimestamps : true,
products : function () {
return this.hasMany(Product, 'category_id');
}
});
// Product model
var Product = bookshelf.Model.extend({
tableName : 'products',
hasTimestamps : true,
category : function() {
return this.belongsTo(Category, 'category_id');
}
});
I tried to insert one category alongside with 3 products following the example given the documentation through a transaction. The insertion worked fine but I can't return all data inserted including the products (It's OK for the category but I get nothing for the newly products).
That is my full code :
bookshelf.transaction(function(t){
var products = req.body.products;
var tableProd = [];
//if (!req.params.idCategory || req.params.idCategory ==0) {
return Category.forge({
name : req.body.name,
code : req.body.code,
tax_percentage : req.body.tax_percentage,
description : req.body.description
})
.save(null, {transacting : t})
.tap(function (category) {
for (var i=0; i < products.length; i++){
tableProd.push({
barcode : products[i].barcode,
cip : products[i].cip,
category_id : category.id,
quantity : products[i].quantity,
retail_price : products[i].retail_price,
description : products[i].description,
name : products[i].name,
DCI_name : products[i].DCI_name,
kind : products[i].kind,
comment : products[i].comment,
status : products[i].status,
critical_threshold : products[i].critical_threshold,
max_threshold : products[i].max_threshold,
date_end : products[i].date_end
});
}
return Promise.map(tableProd, function (info) {
Product.forge(info).save(null, {transacting : t})
})
});
})
.then(function (category) {
var result = category.related('products').pluck('category_id');
console.log('Category' + JSON.stringify(category.toJSON()) + ' resultat: ' + JSON.stringify(result));
res.json({error : false, data : {category : category.toJSON()}})
})
.catch(function (err) {
console.log('Error msg : ' + err.message);
})
What is wrong with this statement :
category.related('products').pluck('category_id')
How can I get all the data inserted : the category including the 3 products ?
Thank you for your help

This works for me;
var ADDRESS = bookshelf.Model.extend({
tableName: 'ADDRESSES'});
var ADDRESSES = bookshelf.Collection.extend({
model: ADDRESS});
var addressArray = new Array();
for(var i=0; i<datas.length; i++) {
addressArray.push({
field1: datas[i].field1,
...
});
}
var addressCollection = ADDRESSES.forge(addressArray);
addressCollection.invokeThen('save').then(function(addressResults) {
console.log(addressResults);
});
You can loop over the addressResults and extract inserted id. Have fun :)

Related

RowDataPacket returns empty object but it is not empty [React/Next]

I've been stressing around trying to fix this and I've burnt myself out. I'm calling my serverless mysql trying to get kanbans from teams. I've used this method multiple times and all were working fine but that is most likely because of they only return single item whilst this returns multiple items.
This is my code which returns empty object.
async function getKanbans(team_id){
let kanbans = [];
await sql_query(`SELECT id, sName FROM table WHERE iTeam = ?`, [team_id])
.then(result => {
result.forEach(kanban => {
// console.log(kanban);
kanbans.push({
id: kanban.id,
name: kanban.sName
});
});
})
.catch(err => {
console.log(err);
});
console.log(kanbans);
return kanbans;
}
As you can see.. I am trying to print kanbans and I do get:
[
{ id: 1, name: 'Kanban_1' },
{ id: 2, name: 'Kanban_2' }
]
of out it. Then I'm trying to return it to the item that called this function and this is how that looks like:
teams.push({
id : team.id,
sName : team.sName,
sColor : team.sColor,
aKanbans : result[0]['selectedTeam'] == team.id ? getKanbans(team.id) : null,
});
(a small snippet of something bigger)
Okay, so now when I try and look at the data response (from the frontend) I get this:
{
"success": true,
"message": "Found teams",
"teams": [
{
"id": 1,
"sName": "Team1",
"sColor": "#fcba03",
"aKanbans": {}
},
{
"id": 2,
"sName": "Team2",
"sColor": "#2200ff",
"aKanbans": null
}
]
}
aKanbans from Team1 is empty, empty object. What the **** do I do? I tried mapping it and still got an empty object. React/javascript is not my main language, I just like to learn. Any suggestions?
You are mixing async / await function with normal Promises handling.
Try to change your getKanbans code like this:
async function getKanbans(team_id) {
let kanbans = [];
try {
const result = await sql_query(
`SELECT id, sName FROM table WHERE iTeam = ?`,
[team_id]
);
result.forEach((kanban) => {
kanbans.push({
id: kanban.id,
name: kanban.sName,
});
});
} catch (err) {
console.log(err);
}
return kanbans;
}
And then populate the teams using (declare the parent async):
teams.push({
id : team.id,
sName : team.sName,
sColor : team.sColor,
aKanbans : result[0]['selectedTeam'] == team.id ? getKanbans(team.id) : null,
});

Create JSON using for loop, Express.js

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

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.

I have an issue with circular reference to JSON using reactjs

I want to serialize circular reference to JSON
This is the part generating the JSON array and it causes a circular reference because it creates a child inside an element and I want to display the result.
const mappedData = this.state.treeData
.filter(data => data.title === "Category")
.map(categ => {
const { id, title, children, subtitle, type } = categ;
function getChildren(children) {
return children
? children.map(child => {
if (child.title === "Item" || child.title === "Group") {
const data = {
id: child.id,
name: child.subtitle,
type: child.type,
children: getChildren(child.children),
child_id: child.children
? child.children.map(child => child.id)
: []
};
if (data.children.length === 0) delete data.children;
if (data.child_id.length === 0) delete data.child_id;
return data;
} else {
return {
id: child.id,
name: child.subtitle,
type: child.type
};
}
})
: [];
}
const data = {
id: id,
name: subtitle,
type: type,
children: getChildren(children),
child_id: children ? children.map(child => child.id) : []
};
if (data.children.length === 0) delete data.children;
if (data.child_id.length === 0) delete data.child_id;
return data;
});
The HTML part that calls the stringify method
<div className="json">
<p> {JSON.stringify(mappedData)}</p>
</div>
I found a Replacer that it works but the JSON result is too long for what I need
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};
JSON.stringify(circularReference, getCircularReplacer());
And here's the result :
[{"id":"7a69fc68","name":{"type":"input","key":null,"ref":null,"props":{"className":"inputSubs","type":"text","placeholder":"Category Name"},"_owner":{"tag":1,"key":null,"stateNode":{"props":{},"context":{},"refs":{},"updater":{},"notificationAlert":{"current":{"props":{},"refs":{"notifications":{"__reactInternalInstance$6qqi1p3qi9b":{"tag":5,"key":null,"elementType":"div","type":"div","return":{"tag":1,"key":null,"return":{"tag":5,"key":null,"elementType":"div","type" .. etc
Any Help ?

Issue with MySQL and SequelizeJS

When I save a new record to the database my date gets updated...
In my input : 15/02/2016
In my database : 2016-02-14 23:00:00
My code :
postSubmit: function (request, response) {
var self = this;
var event = request.body.event;
event.start = (event.start) ? moment(event.start, 'DD/MM/YYYY').format("YYYY-MM-DD 00:00:00") : null;
event.end = (event.end) ? moment(event.end, 'DD/MM/YYYY').format("YYYY-MM-DD 00:00:00") : null;
self.eventDao.save(event, function(modelError, event){
if(modelError){
response.redirect('/event/submit');
}else{
response.redirect('/');
}
});
},