Sequelize - Select on associated table - node.js

My problem:
I am creating an route which will return some informations about a group, it has an id, an user assigned and also has some documents. I just want to show how much documents exists, in SQL would be SELECT COUNT, but how can i do this in this in sequelize?
My code:
async list(req, res){
const docGroups = await DocGroup.findAll({
raw: true,
include: [{
model: User,
as: 'userAssigned'
},
{
model: Document,
as: 'Document'
}
]
}).then(groups => {
const result = groups.map(group => {
return Object.assign(
{},
{
id: group.id,
name: group.name,
userAssinged: group['userAssigned.firstName'],
docAmount: // I want to put documents' count here
}
)
})
console.log(groups)
})
}
What is printed in console.log(groups):
[
{
id: 1,
name: 'pleaseworks',
createdAt: 2020-06-10T02:38:11.531Z,
updatedAt: 2020-06-10T02:38:11.531Z,
'userAssigned.id': 1,
'userAssigned.firstName': 'Please',
'userAssigned.lastName': 'Works',
'userAssigned.email': 'pleaseworks#gmail.com',
'userAssigned.password': '$2a$08$3BA4I4dsaQ3lsHy342344b5P41v5eHWjwqv6dve28nSdqbGvhsdS',
'userAssigned.createdAt': 2020-06-10T02:37:29.062Z,
'userAssigned.updatedAt': 2020-06-10T02:37:29.062Z,
'userAssigned.groupId': null,
'Document.id': 2,
'Document.description': 'deowkdopewkdwe',
'Document.content': 'odepodkewokodwe',
'Document.groupId': 1,
'Document.createdAt': 2020-06-10T02:43:46.005Z,
'Document.updatedAt': 2020-06-10T02:43:46.005Z
}
]

If DocGroup has many Document try something like this:
{
model: Document,
attributes: [[sequelize.fn('COUNT', sequelize.col('id')), 'docAmount']]
as: 'Document'
}

Related

Counting number of associated rows in sequelize

I am trying to find the count of students inside the classStudents association. Here teacher_details table is connected to class_details tables using 'section'
association and class_details tables is connected to student_details table using 'classStudents' association. I have tried the below method but got error ==>
Unknown column 'section->classStudents.studentId' in 'field list'
please let me know the correct procedure to count the associated students count
const getAssignedDetails = async (req, res) => {
try {
const assignedDetails = await Entity.teacherAssignedDetail.findAll({
where: { status: 1, teacherId: req.teacherId },
attributes: [
'role',
[
Sequelize.fn(
'COUNT',
Sequelize.col('section.classStudents.studentId')
),
'studentCount',
],
],
include: [
{
association: 'section',
attributes: ['sectionId', 'className', 'classEmoji'],
include: [
{
association: 'classStudents',
where: { status: 1 },
required: false,
},
],
where: { status: 1 },
},
{
association: 'subjectDetails',
attributes: [['id', 'masterSubjectId'], 'subjectName'],
},
],
});
res.json({
responseCode: 0,
responseMessage: 'Success',
responseData: assignedDetails,
});
} catch (err) {
res.status(500).send(errorHandling(err.message));
}
};

complicated query using sequelize

i have 3 tables .. profile, player, garage
profile has winCount , loseCount
player has username
garage has carNumber
they are all connected with each other using the id from player table (playerId in table garage and profile)
i want to get the
top 20 winCount , username , carnumber
i am trying this code
let racers = await Profile.findAll({
where: {
carRaceWinCount: {
[Op.gt]: 0
}
},
limit: 20,
order: [
['carRaceWinCount', 'DESC']
]
})
.then((races: any) => {
Garage.findAll({
where: {
playerId: races.id
},
attributes : ['carNum']
})
Player.findAll({
where :{
id : races.id
},
attributes : ['username']
})
})
and it is not working
what is the best way to get this query
If you have these associations:
Player.hasMany(Profile, { foreignKey: 'playerId' })
Player.hasMany(Garage, { foreignKey: 'playerId' })
Profile.belongsTo(Player, { foreignKey: 'playerId' })
then the query might look like this
await Profile.findAll({
where: {
winCount: {
[Op.gt]: 0
}
},
limit: 20,
include: [{
model: Player,
include: [{
model: Garage,
// this is important option to query all garames as separate queries, Otherwise you will get wrong count of profiles.
separate: true
}]
}]
order: [
['winCount', 'DESC']
]
})

how to attach or detach record on many to many sequelize association?

I have many to many association like this following model:
const Movie = sequelize.define('Movie', { name: DataTypes.STRING });
const Actor = sequelize.define('Actor', { name: DataTypes.STRING });
const ActorMovies = sequelize.define('ActorMovies', {
MovieId: {
type: DataTypes.INTEGER,
references: {
model: Movie,
key: 'id'
}
},
ActorId: {
type: DataTypes.INTEGER,
references: {
model: Actor,
key: 'id'
}
}
});
Movie.belongsToMany(Actor, { through: ActorMovies });
Actor.belongsToMany(Movie, { through: ActorMovies });
And I succsessfully create Movie when create an Actor record with this following code:
Actor.create({
name: 'Jhony',
movies: [
{ name: 'Movie 1'}, // it will generate Movie with ID 1
{ name: 'Movie 2'} // it will generate Movie with ID 2
]
}, {
include: [ Movie ]
})
but my question how can I attach multiple existing Movie record when creating an Actor?
I already try:
Actor.create({
name: 'Edward',
movieIds: [1, 2]
}, {
include: [ Movie ]
})
and:
Actor.create({
name: 'Edward',
movies: [{id: 1}, {id: 2}]
}, {
include: [ Movie ]
})
But stil didn't work. Anyone can help me, please. Thanks in advance
You can't link existing movies to a new actor while creating it. You need to call setMovies of the new actor model instance:
const actor = await Actor.create({
name: 'Edward',
})
await actor.setMovies([1, 2])
Also, please pay attention that if you execute more than one query that changes something in DB it would be much more reliable to use transactions to turn all this queries into one atomic operation.

How do you seed a mongodb database such that the Keystone 5 CMS recognizes the many-to-many relationships?

Let's say I have two objects: Product and Seller
Products can have multiple Sellers.
A single Seller can sell multiple Products.
The goal is to write a seeding script that successfully seeds my MongoDB database such that Keystone.js's CMS recognizes the many-to-many relationship.
Schemas
Product.ts
import { text, relationship } from "#keystone-next/fields";
import { list } from "#keystone-next/keystone/schema";
export const Product = list({
fields: {
name: text({ isRequired: true }),
sellers: relationship({
ref: "Seller.products",
many: true,
}),
},
});
Seller.ts
import { text, relationship } from "#keystone-next/fields";
import { list } from "#keystone-next/keystone/schema";
export const Product = list({
fields: {
name: text({ isRequired: true }),
products: relationship({
ref: "Product.sellers",
many: true,
}),
},
});
KeystoneJS config
My keystone.ts config, shortened for brevity, looks like this:
import { insertSeedData } from "./seed-data"
...
db: {
adapter: "mongoose",
url: databaseURL,
async onConnect(keystone) {
console.log("Connected to the database!");
if (process.argv.includes("--seed-data")) {
await insertSeedData(keystone);
}
},
},
lists: createSchema({
Product,
Seller,
}),
...
Seeding Scripts (these are the files I expect to change)
I have a script that populates the database (seed-data/index.ts):
import { products } from "./data";
import { sellers } from "./data";
export async function insertSeedData(ks: any) {
// setup code
const keystone = ks.keystone || ks;
const adapter = keystone.adapters?.MongooseAdapter || keystone.adapter;
const { mongoose } = adapter;
mongoose.set("debug", true);
// adding products to DB
for (const product of products) {
await mongoose.model("Product").create(product);
}
// adding sellers to DB
for (const seller of sellers) {
await mongoose.model("Seller").create(seller);
}
}
And finally, data.ts looks something like this:
export const products = [
{
name: "apple",
sellers: ["Joe", "Anne", "Duke", "Alicia"],
},
{
name: "orange",
sellers: ["Duke", "Alicia"],
},
...
];
export const sellers = [
{
name: "Joe",
products: ["apple", "banana"],
},
{
name: "Duke",
products: ["apple", "orange", "banana"],
},
...
];
The above setup does not work for a variety of reasons. The most obvious is that the sellers and products attributes of the Product and Seller objects (respectively) should reference objects (ObjectId) and not names (e.g. "apple", "Joe").
I'll post a few attempts below that I thought would work, but did not:
Attempt 1
I figured I'd just give them temporary ids (the id attribute in data.ts below) and then, once MongoDB assigns an ObjectId, I'll use those.
seed-data/index.ts
...
const productIdsMapping = [];
...
// adding products to DB
for (const product of products) {
const productToPutInMongoDB = { name: product.name };
const { _id } = await mongoose.model("Product").create(productToPutInMongoDB);
productIdsMapping.push(_id);
}
// adding sellers to DB (using product IDs created by MongoDB)
for (const seller of sellers) {
const productMongoDBIds = [];
for (const productSeedId of seller.products) {
productMongoDBIds.push(productIdsMapping[productSeedId]);
const sellerToPutInMongoDB = { name: seller.name, products: productMongoDBIds };
await mongoose.model("Seller").create(sellerToPutInMongoDB);
}
...
data.ts
export const products = [
{
id: 0,
name: "apple",
sellers: [0, 1, 2, 3],
},
{
id: 1,
name: "orange",
sellers: [2, 3],
},
...
];
export const sellers = [
{
id: 0
name: "Joe",
products: [0, 2],
},
...
{
id: 2
name: "Duke",
products: [0, 1, 2],
},
...
];
Output (attempt 1):
It just doesn't seem to care about or acknowledge the products attribute.
Mongoose: sellers.insertOne({ _id: ObjectId("$ID"), name: 'Joe', __v: 0}, { session: null })
{
results: {
_id: $ID,
name: 'Joe',
__v: 0
}
}
Attempt 2
I figured maybe I just didn't format it correctly, for some reason, so maybe if I queried the products and shoved them directly into the seller object, that would work.
seed-data/index.ts
...
const productIdsMapping = [];
...
// adding products to DB
for (const product of products) {
const productToPutInMongoDB = { name: product.name };
const { _id } = await mongoose.model("Product").create(productToPutInMongoDB);
productIdsMapping.push(_id);
}
// adding sellers to DB (using product IDs created by MongoDB)
for (const seller of sellers) {
const productMongoDBIds = [];
for (const productSeedId of seller.products) {
productMongoDBIds.push(productIdsMapping[productSeedId]);
}
const sellerToPutInMongoDB = { name: seller.name };
const { _id } = await mongoose.model("Seller").create(sellerToPutInMongoDB);
const resultsToBeConsoleLogged = await mongoose.model("Seller").findByIdAndUpdate(
_id,
{
$push: {
products: productMongoDBIds,
},
},
{ new: true, useFindAndModify: false, upsert: true }
);
}
...
data.ts
Same data.ts file as attempt 1.
Output (attempt 2):
Same thing. No luck on the products attribute appearing.
Mongoose: sellers.insertOne({ _id: ObjectId("$ID"), name: 'Joe', __v: 0}, { session: null })
{
results: {
_id: $ID,
name: 'Joe',
__v: 0
}
}
So, now I'm stuck. I figured attempt 1 would Just Work™ like this answer:
https://stackoverflow.com/a/52965025
Any thoughts?
I figured out a solution. Here's the background:
When I define the schema, Keystone creates corresponding MongoDB collections. If there is a many-to-many relationship between object A and object B, Keystone will create 3 collections: A, B, and A_relationshipToB_B_relationshipToA.
That 3rd collection is the interface between the two. It's just a collection with pairs of ids from A and B.
Hence, in order to seed my database with a many-to-many relationship that shows up in the Keystone CMS, I have to seed not only A and B, but also the 3rd collection: A_relationshipToB_B_relationshipToA.
Hence, seed-data/index.ts will have some code that inserts into that table:
...
for (const seller of sellers) {
const sellerToAdd = { name: seller.name };
const { _id } = await mongoose.model("Seller").create(sellerToAdd);
// Product_sellers_Seller_products Insertion
for (const productId of seller.products) {
await mongoose
.model("Product_sellers_Seller_products")
.create({
Product_left_id: productIds[productId], // (data.ts id) --> (Mongo ID)
Seller_right_id: _id,
});
}
}
...

join same table in sequelize and print in excel

I want to print parent name in excel
this is my code
function getReportT0Print(req, res) {
return new Promise((resolve, reject) => {
Product.findAll({
where: {
$and: [
{
public: true,
visible: true,
ancestry: {
$not: null,
},
},
],
},
include: [
{
model: ormDb.Document,
required: false,
},
],
attributes: ["name", "slug", "folder_path"],
})
.then(function (data) {
// console.log("data" + data.length);
var rows = [];
rows.push(["Product Name", "Slug", "File Path", "Product Parent Name"]);
data.map(function (product) {
rows.push([
product.name,
product.slug,
product.folder_path,
(here i need to print parent name)
]);
});
var workbook = new Excel.Workbook();
var sheet = workbook.addWorksheet("products_with_tags");
sheet.addRows(rows);
resolve(workbook);
return res.send("successfull");
})
.catch(function (err) {
reject(err);
});
});
}
i can print name, slug,folder_path but i don't know how to print parent name in excel file
as parent name is not present but i have given parent_id in place of parent name and want to print parent name
my SQl table look like this
("id" "name" "version" "published" "reviewed" "visible" "public", "parent_id")
You need to register an association between two Product models like this:
Product.belongsTo(Product, { foreignKey: 'parent_id', as: 'parent' });
You can place it in some module outside model's module file where you create Sequelize instance, for example.
To use this association you need to use the same include option as you did with Document:
Product.findAll({
where: {
$and: [
{
public: true,
visible: true,
ancestry: {
$not: null,
},
},
],
},
include: [
{
model: Product,
as: 'parent',
required: false, // or true if parent_id is required field
// or you wish to get all products with parents
attributes: ["name", "slug", "folder_path"],
},
{
model: ormDb.Document,
required: false,
},
],
attributes: ["name", "slug", "folder_path"],
})

Resources