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...
});
Related
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")
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;
});
For example, I have
[
{ name: "John" },
{ name: "Mike" },
{ name: "Homer" },
{ name: "Bart" },
{ name: "Dmitry" },
{ name: "Dan" }
]
How will I choose many objects with mongoose, if I use .limit(2) I will get [{ name: "John" }, { name: "Mike" }], I need to choose [{ name: "Bart" }, { name: "Dmitry" }]. In default JS this method looks like .slice(3,5). How will I do it with mongoose?
You can try something like this:
Model.find({name: {$in: ["Bart", "Dmitry"]}});
You can achieve this in mongodb by using skip(3).limit(2).
In Mongoose you can achieve this with myModel.find({}, 'name', {skip: 3, limit: 2}), you just have to insert values of skip and limit you want in third parameter of find.
Here's documentation with an example of skip and here's a link to a more popular answer of similar problem.
Edit: Note that this is a short-sighted solution, you should use something else for large or changing database.
I'm newbie for Sequelize
I have a problem with "Nested Eager Loading"
I have 2 Table with 1-to-many relationship
Comment Table
User Table
I use this code for the query
Comment.findAll({
include: [User]
})
I got
{
id: 1,
comment: "test",
user: {
id: 3,
name: "someone"
}
}
But I expected result like this
{
id: 1,
comment: "test",
user_id: 3,
user_name: "someone"
}
I read several stackoverflow post it has a solution but work for version 3.3
Comment.findAll({
attributes: ['id', 'name', ['user.id','user_id'], ['user.name','user_name']]
include: [{ model: User, attributes:[], nested: false, required: true }]
})
Comment.findAll({
attributes: ['id', 'name', [Sequelize.col('user.id'),'user_id'], [Sequelize.col('user.name'),'user_name']]
include: [{ model: User, attributes:[], nested: false, required: true }]
})
but it's not work for me.
now I use sequelize 5.5.1 how can I implement it.
Can someone help me, please?
You can use this code to get the desired output:
Since Sequelize is promised based , it is recommend to use then and catch.
Comment.findAll({
include: [User]
}).then(result=>
{
let obj=
{
id: result.item,
comment: result.comment,
user_id: result.user.id,
user_name: result.user.name
};
console.log(JSON.stringify(obj));
}).catch(err=>
{
console.log(err);
});
I'm trying to implement a minimal emberJs app using fixtures and a one-to-many relation between two models:
App.store = DS.Store.create({
revision: 11,
adapter: 'DS.FixtureAdapter'
});
App.Album = DS.Model.extend({
Name: DS.attr("string"),
Songs: DS.hasMany('App.Song')
});
App.Song = DS.Model.extend({
Name: DS.attr("string"),
Album: DS.belongsTo('App.Album')
});
App.Album.FIXTURES = [
{
id: 1,
Name: 'foo'
},
{
id: 2,
Name: 'bar'
}
];
App.Song.FIXTURES = [
{
id: 1,
Album_id: 1,
Name: "asdf"
},
{
id: 2,
Album_id: 2,
Name: "Test"
}
];
I can access the Album model through the console like this
App.Album.find(1).get('Name') # => foo
Whenever I try access the Songs property trough the relation between album and song I get undefined:
App.Album.find(1).get('Songs').objectAt(0) # undefined
Any hints what I might be doing wrong here?
You haven't defined which Songs an Album has. You need to specify Songs: [1,2,3] in your Album model.
(Quite sure it's Songs, but it may Song_ids.)