I need to get lists of interests with data aboit it and count customers that subscibed to interest
I have many-to-one relation between interests and customers.
This is what only might to do
const list = await this.interestRepository
.createQueryBuilder('interest')
.leftJoinAndSelect("interest.translations", "translations")
.leftJoinAndSelect("interest.customers", "customers")
.getMany()
And this is the result:
list [
Interest {
id: 'YJnu_8bpzMSrFiztDl1zH',
creationDate: 2022-12-19T16:49:55.090Z,
countryCode: 'LTU',
rank: 2,
status: 'active',
translations: [ [InterestTranslation], [InterestTranslation] ],
customers: [ [Customer] ]
},
Interest {
id: '-h1UPpOSkw4TqcTc7F5Ej',
creationDate: 2022-12-19T16:57:47.718Z,
countryCode: 'USA',
rank: 1,
status: 'active',
translations: [ [InterestTranslation], [InterestTranslation] ],
customers: []
}
]
But i want to count the customers, not get all of them, because it could be thouthands of them and it will affect on request duration.
if I understood correctly you need put this
.loadRelationCountAndMap('interest.customers', 'interest.customers')
instead of
.leftJoinAndSelect("interest.customers", "customers")
Related
I'm trying to create a new object that only contains the a product array with the seller I req. I have an order object that has a product array. I'd like to return a specific seller. I tried:
const newOrders = orders.map((element) => {
return {
...element,
product: element.product.filter(
(seller) => seller === req.currentUser!.id
),
};
});
does mongoose have a preferred method for doing what I bring to achieve? I've read through the find queries but none of the methods seem useful to this use case.
orders: [
{
userId: "638795ad742ef7a17e258693",
status: "pending",
shippingInfo: {
line1: "599 East Liberty Street",
line2: null,
city: "Toronto",
country: "CA",
postal_code: "M7K 8P3",
state: "MT"
},
product: [
{
title: "new image",
description: "a log description",
seller: "6369589f375b5196f62e3675",
__v: 1,
id: "63737e4b0adf387c5e863d33"
},
{
title: "Mekks",
description: "Ple",
seller: "6369589f375b5196f62e3675",
__v: 1,
id: "6376706808cf1adafd5af32f"
},
{
title: "Meeks Prodyuct",
description: "long description",
seller: "63868795a6196afbc3677cfe",
__v: 1,
id: "63868812a6196afbc3677d06"
}
],
version: 1,
id: "6388138170892249e01bdcba"
}
],
Im sure this can be improved, doesn't feel that its the best way possible but it gets the result. Like the previous answer you have to find first the order the seller is in then find the products than filter the seller by the id. I'm using typescript and there's a bug https://github.com/microsoft/TypeScript/issues/50769 so you have to use the bracket notation.
const orders = await Order.find({
"product.seller": req.currentUser!.id,
});
const allOrders = orders[0].product;
const sellerOrders = allOrders.filter((obj) => {
return obj["seller"] === req.currentUser!.id;
});
In my app, I need an array of diagnosis codes in the form of
['Z57.1', 'Z74.3', 'M51.2'] so I can have access to each of them.
However, when mapping through diagnosis codes, I get [Array(3)] in the console instead of ['Z57.1', 'Z74.3', 'M51.2'], meaning I can't get access to the codes.
How do you map through patient.entries to return ['Z57.1', 'Z74.3', 'M51.2'] in the console instead of [Array(3)]?
const patient = {
id: 'd2773598-f723-11e9-8f0b-362b9e155667',
name: 'Martin Riggs',
dateOfBirth: '1979-01-30',
ssn: '300179-777A',
gender: Gender.male,
occupation: 'Cop',
entries: [
{
id: 'fcd59fa6-c4b4-4fec-ac4d-df4fe1f85f62',
date: '2019-08-05',
type: 'OccupationalHealthcare',
specialist: 'MD House',
employerName: 'HyPD',
diagnosisCodes: ['Z57.1', 'Z74.3', 'M51.2'],
description:
'Patient mistakenly found himself in a nuclear plant waste site without protection gear. Very minor radiation poisoning. ',
sickLeave: {
startDate: '2019-08-05',
endDate: '2019-08-28',
},
},
],
},
const codes = patient?.entries.map(c => c.diagnosisCodes);
const codes returns:
[Array(3)]
0
:
(3) ['Z57.1', 'Z74.3', 'M51.2']
length
:
1
[[Prototype]]
:
Array(0)
You could use Array.prototype.flatMap.
It works like map, but flattens nested arrays into a single monolithic array.
Your main issue is that you have n-number of entries with m-number of diagnosis codes. Your resulting array of codes will be 2-dimensional. Flattening the matrix will result in a linear array.
const main = () => {
const codes = patient.entries.flatMap(c => c.diagnosisCodes);
console.log(codes);
};
const Gender = { male: 'Male', female: 'Female', other: 'Other' };
const patient = {
id: 'd2773598-f723-11e9-8f0b-362b9e155667',
name: 'Martin Riggs',
dateOfBirth: '1979-01-30',
ssn: '300179-777A',
gender: Gender.male,
occupation: 'Cop',
entries: [{
id: 'fcd59fa6-c4b4-4fec-ac4d-df4fe1f85f62',
date: '2019-08-05',
type: 'OccupationalHealthcare',
specialist: 'MD House',
employerName: 'HyPD',
diagnosisCodes: ['Z57.1', 'Z74.3', 'M51.2'],
description: 'Patient mistakenly found himself in a nuclear plant waste site without protection gear. Very minor radiation poisoning. ',
sickLeave: {
startDate: '2019-08-05',
endDate: '2019-08-28',
}
}]
};
main();
const patient = {
id: 'd2773598-f723-11e9-8f0b-362b9e155667',
name: 'Martin Riggs',
dateOfBirth: '1979-01-30',
ssn: '300179-777A',
//gender: Gender.male,
occupation: 'Cop',
entries: [
{
id: 'fcd59fa6-c4b4-4fec-ac4d-df4fe1f85f62',
date: '2019-08-05',
type: 'OccupationalHealthcare',
specialist: 'MD House',
employerName: 'HyPD',
diagnosisCodes: ['Z57.1', 'Z74.3', 'M51.2'],
description:
'Patient mistakenly found himself in a nuclear plant waste site without protection gear. Very minor radiation poisoning. ',
sickLeave: {
startDate: '2019-08-05',
endDate: '2019-08-28'
}
}
]
};
const codes = patient.entries.reduce((t, v) => [...t, ...v.diagnosisCodes], []);
console.log(codes);
I'm new to mongoose, I'm confuse while create the query. Can you help me?
I have video collection like this:
{
_id: 603dea86cef0aed372cd9ce6,
category: [
"603dea86cef0aed372cd9cd8", // array of category objectId
"603dea86cef0aed372cd9cd9"
],
hashtag: [
"603dea86cef0aed372cd9cee" // array of hashtag objectId
],
video_id: '6925666264463576320',
share_id: 'greate_video',
author: 603dea86cef0aed372cd9cd8, // ref to Author objectId
cover: 'https://path.to/img.jpg',
post_by: 60083f24edae03650406ad48, // ref to User objectId
status: 1, // enum status [0, 1, 2]
date: 2021-03-02T07:34:30.635Z
}
I want to query to get data with structure like below. I mean, I will find by _id and get related data form other collections, more than that, I want the video list show with status 1, 2 (not 0) and sort by video _id: -1.
{
_id: 603dea86cef0aed372cd9ce6,
category: [
{_id: "603dea86cef0aed372cd9cd8", category_name: Tech},
{_id: "603dea86cef0aed372cd9cd9", category_name: Mobile},
],
hashtag: [
{_id: "603dea86cef0aed372cd9cee", hashtag_name: tech},
],
video_id: '6925666264463576320',
share_id: 'greate_video',
author: {_id: "603dea86cef0aed372cd9cd8", author_name: Nani, avatar: 'https://path.to/avatar.jpg'},
cover: 'https://path.to/img.jpg',
post_by: {_id: "603dea86cef0aed372cd9cd8", user_name: Username, avatar: 'https://path.to/avatar.jpg'},
status: 1,
date: 2021-03-02T07:34:30.635Z
}
How do I write the aggregation query? I tried with query like this but doesn't work, it show empty [] result.
const videoList = await Video.aggregate([
{
$lookup:
{
from: 'Author',
localField: "author",
foreignField: "_id",
as: "author_info"
}
}
])
Thank you
name of collection usually written in plural lowercase letters so I think you should change Author to authors
I'm writing a test to check that a function in my Node.js application which returns this JSON structure:
}
id: 1,
name: 'John Doe',
email: 'j#doe.com',
phone: '+123',
suppliers: [
{
id: 1,
name: 'Supplier1'
}
]
}
I have this expect:
expect(res.body.users[0]).to.be.an.instanceof(Object)
.that.includes.all.keys([
'id',
'name',
'suppliers',
]);
I also want to check there are details in suppliers. I could just add this in another expect:
expect(res.body.users[0].suppliers[0]).to.be.an.instanceof(Object)
.that.includes.all.keys([
'id',
'name',
]);
Is it possible to combine both into one expect statement though?
I have a many to many association like this:
Squad.belongsToMany(Member, {through: Membership});
Member.belongsToMany(Squad, {through: Membership});
How do I find all the Squads, and for each squad, show me the squad name and an array with the Members that each squad has associated with it?
UPDATED WITH WHAT I'VE BEEN TRYING AND WHAT RESULTS I GET:
I've been trying things like this:
Squad.findAll({
include: [{
model: Member,
required: true
}]
}).then(squads => {
// The rest of your logics here...
});
Here's a sample of what I get:
{ id: 3,
name: 'Knicks',
city: 'NYC',
state: 'NY',
'members.id': 3,
'members.name': 'Carmelo',
'members.city': 'NYC'
},
{ id: 3,
name: 'Knicks',
city: 'NYC',
state: 'NY',
'members.id': 2,
'members.name': 'Penny',
'members.city': 'Orlando',
'members.state': 'Florida'
}
But what I want is not multiples of the same object and individual member info. I'm trying to get something more like this:
{
id: 2,
name: 'Lakers',
members: [ memberInfo, memberInfo, memberInfo]
}
Is there a way to do that?
Assuming that you modeled your relations correctly, then you should be able to do something like
Squad.findAll({
include: [{
model: Member,
required: true
}]
}).then(squads => {
// The rest of your logics here...
});