Dealing with SQL cartesians in nodeJS - node.js

I've got a query that is coming back with cartesians because one of the table joins can have many results. The use case is I have a company that can have many locations.
Here's the response I'm getting in my query:
[
{
// this is the company info
oid: 31,
companyName: 'Foo Bar Inc',
avatar: 'http://placehold.it/100x100',
bannerImage: 'http://placehold.it/800x200',
// here starts the location
name: 'Foo Bar Port',
address: '1234 West 31 Street',
city: 'New York',
state: 'New York'
},
{
oid: 31,
companyName: 'Foo Bar Inc',
avatar: 'http://placehold.it/100x100',
bannerImage: 'http://placehold.it/800x200',
name: 'Foo Bar Warehouse',
address: '644 Main Street',
city: 'Los Angeles',
state: 'California'
}
]
I would eventually like to get this to turn into:
{
oid: 31,
companyName: 'Foo Bar Inc',
avatar: 'http://placehold.it/100x100',
bannerImage: 'http://placehold.it/800x200',
locations: [
{
name: 'Foo Bar Port',
address: '1234 West 31 Street',
city: 'New York',
state: 'New York'
},
{
name: 'Foo Bar Warehouse',
address: '644 Main Street',
city: 'Los Angeles',
state: 'California'
}
]
}
What is the best way to handle this?

This below example if you use Sequelize ORM in node.js:
Here Company and Location is model.
// Company.js
// ...
Company.associate = function(models) {
// Using additional options like CASCADE etc for demonstration
// Can also simply do Company.belongsTo(models.Location);
Company.belongsTo(models.Location, {
onDelete: "CASCADE",
foreignKey: {
allowNull: false
}
});
}
// ...

Related

Mongoose Aggregate - Group by field from array

For one of my project, I am working on MongoDB database and Mongoose as ODM in nestjs project.
One of my collection is looks like this data:
[
{
_id: '56cb91bdc3464f14678934ca',
organization: 'New Circle Ltd',
rooms: [
{
name: 'Alex',
workId: 'abc',
},
{
name: 'John',
workId: 'cde',
},
{
name: 'John',
workId: 'abc',
},
{
name: 'Alex',
workId: 'cdlw',
},
{
name: 'Alex',
workId: 'rps',
},
],
},
];
The requirement is to get one data by id and the data should be like the data provided bellow.
{
_id: '56cb91bdc3464f14678934ca',
organization: 'New Circle Ltd',
rooms: [
{
name: 'Alex',
workIds: ['abc', 'cdlw', 'rps'],
},
{
name: 'John',
workIds: ['cde', 'abc'],
},
],
},
Please suggest me how can I get this data

MongoDB data modeling help needed (Opinions on specific data modeling)

I am creating a web application (Email Marketing Platform) and I am using MERN stack i.e. MongoDB as database, I am not very familiar with NoSQL.
In my application I need to store many contacts for every user (Each user will have their own contacts). I do have a users collection for storing user's information but I am confused on how to store their contacts, I have 3 options I would like to know advantage and disadvantage of these methods if any:
Storing in the user document (Using an array but having many contacts let say 50000 will create an issue for a single document, It's what I think.)
// User document
{
_id: ObjectId("6257e229244ccce02d96169e"),
name: 'Areeb Ahmad',
username: 'areeb',
password: '123',
contacts: [
{
_id: ObjectId("625b271536a6a83858b91d26"),
name: 'contact1',
email: 'contact1#gmail.com',
address: 'Some XYZ Street',
tags: ['tag1', 'tag2', 'tag3'],
source: 'website form',
age: 18,
gender: 'male',
isSubscribed: true,
dateAdded: 'some date',
dateModified: 'Some Date',
}, {
_id: ObjectId("625b271536a6a15788b91d26"),
name: 'contact2',
email: 'contact2#gmail.com',
address: 'Some XYZ Street',
tags: ['tag1', 'tag2', 'tag3'],
source: 'website form',
age: 28,
gender: 'female',
isSubscribed: false,
dateAdded: 'some date',
dateModified: 'Some Date',
}
]
__v: 0
}
Storing all the contacts in separate collection but store their id's in the user document but I think having large amount of contacts can cause issues.
// User Document
{
_id: ObjectId("6257e229244ccce02d96169e"),
name: 'Areeb Ahmad',
username: 'areeb',
password: '123',
contacts: [
ObjectId("625b271536a6a83858b91d26"),
ObjectId("178b271534a6a83858b91d26"),
ObjectId("741b271536a6a83858b91d26"),
ObjectId("854b271536a6a83858b91d26")
]
__v: 0
}
Storing all the contacts in separate collection but store their owner's (users') id in them.
// Contacts Document
{
_id: ObjectId("625b271536a6a15788b91d26"),
user_id : ObjectId("62530cdbf7b28d7da57634af"),
name: 'contact2',
email: 'contact2#gmail.com',
address: 'Some XYZ Street',
tags: ['tag1', 'tag2', 'tag3'],
source: 'website form',
age: 28,
gender: 'female',
isSubscribed: false,
dateAdded: 'some date',
dateModified: 'Some Date',
}
Please let me know which one should I go with, and why, Any other suggestions or ways are more than welcome.

how can I add nestead array of objects using convert-excel-to-json

I am trying to insert data from excel sheet using convert-excel-to-json npm. I am able to basic format of my data but i want to add also images as a nested array.
Here Is my code:
app.post("/upload-excel", async (req, res) => {
const newpath = __dirname + "/files/";
const file = req.files.file;
const filename = file.name;
const worksheetsArray = xlsx.parse(filename); // parses a file
const excelData = excelToJson({
sourceFile: filename,
sheets: [{
// Excel Sheet Name
name: worksheetsArray[0].name,
// Header Row -> be skipped and will not be present at our result object.
header: {
rows: 1
},
// Mapping columns to keys
columnToKey: {
A: '_id',
B: 'name',
C: 'address',
D: 'age',
}
}]
});
console.log(excelData);
});
The above code output is:
{
Customers: [
{ _id: 1, name: 'Jack Smith', address: 'Massachusetts', age: 23 },
{ _id: 2, name: 'Adam Johnson', address: 'New York', age: 27 },
{
_id: 3,
name: 'Katherin Carter',
address: 'Washington DC',
age: 26
},
{ _id: 4, name: 'Jack London', address: 'Nevada', age: 33 },
{ _id: 5, name: 'Jason Bourne', address: 'California', age: 36 }
]
}
The expected output is: Here i have added extra images
{
Customers: [
{ _id: 1, name: 'Jack Smith',images:[{id:1, src:"sadasd.com"}], address: 'Massachusetts', age: 23 },
{ _id: 2, name: 'Adam Johnson', address: 'New York',images:[{id:1, src:"sadasd.com"}] age: 27 },
{
_id: 3,
name: 'Katherin Carter',
address: 'Washington DC',
age: 26,
images:[{id:1, src:"sadasd.com"}, {id:1, src:"sadasd.com"}],
{ _id: 4, name: 'Jack London', address: 'Nevada',images:[{id:1, src:"sadasd.com"}], {id:1, src:"sadasd.com"}], age: 33 },
{ _id: 5, name: 'Jason Bourne',images:[{id:1, src:"sadasd.com"}, address: 'California', age: 36 }
]
}

firebase callable node function

I try to use a node function in firebase callable function and wehn I try to use it as described I see this warning on VS code. any help? on what I can do
module "c:/Users/firat/Desktop/vuedg3/functions/node_modules/iyzipay/lib/Iyzipay"
Could not find a declaration file for module 'iyzipay'. 'c:/Users/firat/Desktop/vuedg3/functions/node_modules/iyzipay/lib/Iyzipay.js' implicitly has an 'any' type.
Try npm install #types/iyzipay if it exists or add a new declaration (.d.ts) file containing declare module 'iyzipay';ts(7016)
and this callable function return null when I try and call it from web app
this is my entire code
exports.trypay = functions.https.onCall((data, context) => {
var Iyzipay = require('iyzipay');
var iyzipay = new Iyzipay({
apiKey: "sandbox-11",
secretKey: "sandbox-11",
uri: 'https://sandbox-api.iyzipay.com'
});
var request = {
locale: Iyzipay.LOCALE.TR,
conversationId: '123456789',
price: '1',
paidPrice: '1.2',
currency: Iyzipay.CURRENCY.TRY,
installment: '1',
basketId: 'B67832',
paymentChannel: Iyzipay.PAYMENT_CHANNEL.WEB,
paymentGroup: Iyzipay.PAYMENT_GROUP.LISTING,
paymentCard: {
cardHolderName: 'John Doe',
cardNumber: '5528790000000008',
expireMonth: '12',
expireYear: '2030',
cvc: '123',
registerCard: '0'
},
buyer: {
id: 'BY789',
name: 'John',
surname: 'Doe',
gsmNumber: '+905350000000',
email: 'email#email.com',
identityNumber: '74300864791',
lastLoginDate: '2015-10-05 12:43:35',
registrationDate: '2013-04-21 15:12:09',
registrationAddress: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1',
ip: '85.34.78.112',
city: 'Istanbul',
country: 'Turkey',
zipCode: '34732'
},
shippingAddress: {
contactName: 'Jane Doe',
city: 'Istanbul',
country: 'Turkey',
address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1',
zipCode: '34742'
},
billingAddress: {
contactName: 'Jane Doe',
city: 'Istanbul',
country: 'Turkey',
address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1',
zipCode: '34742'
},
basketItems: [
{
id: 'BI101',
name: 'Binocular',
category1: 'Collectibles',
category2: 'Accessories',
itemType: Iyzipay.BASKET_ITEM_TYPE.PHYSICAL,
price: '0.3'
},
{
id: 'BI102',
name: 'Game code',
category1: 'Game',
category2: 'Online Game Items',
itemType: Iyzipay.BASKET_ITEM_TYPE.VIRTUAL,
price: '0.5'
},
{
id: 'BI103',
name: 'Usb',
category1: 'Electronics',
category2: 'Usb / Cable',
itemType: Iyzipay.BASKET_ITEM_TYPE.PHYSICAL,
price: '0.2'
}
]
};
iyzipay.payment.create(request, function (err, result) {
return('result:'+result + 'error:'+err);
});
})

How to assign EmbeddedDocument to Objet's key in mongoengine

I have a data structure that looks like this:
addresses: [
{
type: 'home',
street: 'street',
city: 'city',
zipcode: 'zpipcode',
},
{
type: 'work',
street: 'street',
city: 'city',
zipcode: 'zpipcode',
}
]
I want to model it like this
addresses: {
home: {
street: 'street',
city: 'city',
zipcode: 'zpipcode',
},
work: {
street: 'street',
city: 'city',
zipcode: 'zpipcode',
}
}
I am using now GenericEmbeddedDocumentField but no luck so far.
I found a solution. Have a look at below code. Remember to import mongoengine classes mentioned in the example (Document, MapField, etc..)
Example of model(s) definition
class Address(EmbeddedDocument):
street = StringField(required=True, max_length=256)
zipcode = StringField(required=True, max_length=16)
city = StringField(required=True, max_length=32)
country = StringField(default="Poland")
class User(Document):
email = EmailField(required=True)
addresses = MapField(field=EmbeddedDocumentField(Address))
Example of usage
user = User(email='test#mail.com')
user.addresses['home'] = Address(street='street', zipcode='zip', city='city')
user.save()

Resources