How to get the total quantity of products sold? Node - node.js

In the product table add one field like sellcounter and do following the operation.
After placing an order make one update query in product Table Like...
await productModel.updateAll({
id: product.id
}, {
sellcounter: product.sellcounter + 1
});
Above code is for loopback Node

The idea here is to increment the number of sales by one on a specific product.
To do so, you'll need to use the method findOne or findById to update the specific product.
The resulted code should look like this (assuming that you have the product object with its id):
const productToUpdate = await productModel.findById(product.id);
await productToUpdate.updateAttributes({ sellcounter: product.sellcounter + 1 });

Related

Perform check on record before performing update with Prisma

I'm creating the backend for a simple app which allows users to create, update, and delete products. Using Express as my framework, with Postgres as my DB and Prisma, which I'm new to, as my ORM. Users and products have a one-to-many relationship. Prisma's documentation states that when updating a record, you should use the update method - so to update the name of a product with a given ID, your code would look something like this:
export const updateProduct = async (req, res) => {
const [productID, newProductName, userID] = [req.params.id, req.body.name, res.locals.user.id];
const product = await prisma.product.update({
where: {
id: productID,
},
data: {
name: newProductName
}
});
res.status(200);
res.json(product);
};
However, there's a problem here - I'm not checking to see that the product with the provided ID belongs to the user that has sent the request to update it. I have the ID of the user who has sent the request in the variable userID, and each product in the DB has a field belongsToID which is set to the ID of the user that the product belongs to. I should theoretically therefore be able to modify my query to get the product with the specified ID and a matching belongsToID like so:
export const updateProduct = async (req, res) => {
const [productID, newProductName, userID] = [req.params.id, req.body.name, res.locals.user.id];
const product = await prisma.product.update({
where: {
id: productID,
belongsToID: userID
},
data: {
name: newProductName
}
});
res.status(200);
res.json(product);
};
That, however, does not work - I get the following error: Type '{ id: any; belongsToID: any; }' is not assignable to type 'ProductWhereUniqueInput'. Object literal may only specify known properties, and 'belongsToId' does not exist in type 'ProductWhereUniqueInput'.ts(2322).
It appears that when trying to do a 'findUnique', Prisma doesn't allow non-unique fields to be used in the query (even if the combination of both fields is unique, as is the case here). I do get that logically, my query doesn't make much sense - the ID alone is already enough to find a unique entry without the second field, so in that sense, the second field is totally redundant. Yet how else am I meant to check that the belongsToID is what it should be before updating the record? Is there somewhere else within the object passed to .update where I can provide a check to be performed on the retrieved record before performing the update?
I believe that creating an index would allow me to query for both fields at once - but why should I have to create an index when the ID (which is already indexed) alone is all I need to retrieve the record I need? What I really need is a way to perform a check on a retrieved record before performing the update when using Prisma.table_name.update(), not a way to query for something with a unique combination of fields.

How to write a WHERE prop FROM value TO value query in Nest JS TypeORM

I need to find posts from the Post table where price property is either more than 1 value or lower than 2 value, min-max price kind of a thing, how to write a query for that? What should I write into the options object?
const posts = await this.postRepo.find({
where: {
price: Between(1, 100),
},
});
Can you try this? Or else you can also use createQueryBuilder to write more complex queries.

insert and update multiple documents mongodb

I know there's a lot of threads about this subject - but i still didn't find anything that matches my situation.
There is a big database with companies and products schema's.
Each company uploads their products, (product has "company" field with the mongo id of the company)
My operation goes like this -
Company uploads array of products.
Each product has his own productId.
I need to insert all the products in to the DB but -
If i find product with the same productId - update it - if not - insert a new product.
Change some fields (change product "status" to "deleted") to all of the products that belongs to that company in the DB, that didn't match any of the product id's (from the array of products the user uploaded).
I'm searching for a better solution than the one i'm using, my process goes like this -
fetching all the company's products.
looping through all of the products - and updating a field (status = "deleted") building a mapping object for each product, so i can identify it and check if it exists in the uploaded array.
looping through the company's array (with async library), checking if product exists (in the mapping array), if exists - updating it, if not - create a new product.
It feels very sloppy and i'm sure there is a better way to do it.
the thing i tried to use is -
await Product.updateMany({ productStatus: { $ne: 'manual'} , company: {$eq: company._id}}, { $set: {status: 'deleted' }});
and then
Product.bulkWrite(
productsArray.map((row) =>
({
updateOne: {
filter: { productId: row.productId, company: row.company },
update: row,
upsert: true
}
})
)
)
It was super slow (my method was faster even thought it's more complicated)
If i find product with the same productId - update it - if not - insert a new product.
You can use upserts, which is a find-and-modify operation with upsert: true set. Pass the whole product document.
Change some fields (change product "status" to "deleted") to all of the products that belongs to that company in the DB, that didn't match any of the product id's (from the array of products the user uploaded).
You can use $nin to update the status on all products whose ids are not in the list of currently available products.

Sails.js: How to find records based on values in associated collection?

I'm looking for a way to make sub-query using Sails.js Waterline. The record has an association with Charge model.
I would expect something like that to work, but that doesn't seem to be supported:
var topRecords = await Record.find({'charge.paid':true});
The closest I got was this:
var topRecords = await Record.find().populate('charge',{paid:true});
but the problem is that it still returns all the Records regardless, just doesn't populate the records that do not match populate where statement.
The reason why I can't search for charges first is that I want to sort the data based on one of the values in Record.
You can fetch the Charges then use .map to get the records from there.
const topCharges = await Charge.find({ paid: true }).populate('records');
const topRecords = topCharges.map(charge => charge.record);

Sequelize configuration to retrieve total count with details

I am working with node sequelize with postgres database.
I am loading paginated records to my UI, now I need to get total records count with the same query which I am using to retrieve paginate records.
Anyone, please give the sample sequelize configuration to do the same.
Please see my expected sample postgres query to clarify my question
SELECT count(*) over() as total ,name FROM students WHERE gender='male' LIMIT 2
Thanks in advance
If you want to avoid specifying SQL, you can also use findAndCountAll
You can't do that with sequelize, but you can do through 2 separate queries, one to get the data you need and the other one to get the total count.
first one :
await Model.findAll({ where: { columnName: condition }});
second one :
await Model.count({ where: { columnName: condition }});
if you want to do that in one query which is maybe not the best way (because you adding metadata for each result which is not metadata related to the model) you can create a raw query like that:
await sequelize.query('select count(*) over(), name from table where condition', { model: Model });
I hope my explanation will help you :),
Have a nice day!
You can use findAndCountAll for this purpose.
findAndCountAll - Search for multiple elements in the database, returns both data and total count
Here is an example:
const getStudents = async params => {
const { count, rows: students } = await Student.findAndCountAll({
where: {
gender: 'male',
},
limit: DEFAULT_PAGE_SIZE,
order: [['id', 'ASC']],
...params,
});
return { count, students };
}
params is an object with limit and offset properties that overwrite default limit and offset.
Note that you may need to pass distinct: true as well in case you include other models in a query.
You can count data in two ways
With data (findAndCountAll)
Without Data (count)
1: With data
const students = await students.findAndCountAll({
where: {
gender = "male"
}
});
console.log(students)
It will return Count students where gender is male and data of that students
2: Without Data
const students = await students.count({
where: {
gender = "male"
}
});
console.log(students)
It will return only Count students where gender is male

Resources