return updated entity with entityRepository - nestjs

Is there any way to update an entity and return the result of the operation USING entity repository and NOT query Builder?
const result = await this.shipmentRepository.createQueryBuilder('sh')
.update()
.set({ ...infoToUpdate })
.where('shipment_number = :shipmentNumber', { shipmentNumber })
.returning("*")
.execute()
return result.raw[0]
I'm using this ^, this works properly but I want to know if I can do it using this syntaxis
const result = await this.shipmentRepository.update({ shipment_number: shipmentNumber }, infoToUpdate)
TypeORM documentation doesnt say anything about it
Can you help me? Thank u a lot!

Related

How to Update All Documents in a Collection With Thousands of Documents in FireStore with Firebase Admin?

Updated to reflect Firebase-Admin, rather than v9
New Update: solution at the bottom
How to update a single field (in a map) for all documents in a collection with thousands of documents -- in firebase-admin/firestore (10.0.2)? I attempted to use this:
import { getFirestore } from 'firebase-admin/firestore'
const db = getFirestore()
db.collection("users").get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
doc.ref.update({
"words.subscription": 0
})
})
})
I use it within a Node.js (v12) cloud function. The function runs, I see no errors, but none of the documents are updated. Previously, I attempted to use set() because some documents may not have the field, but Frank let me know update() can update fields that don't exist too.
However, this updated code also does not update all the documents in the 'users' collection.
Thank you in advance.
Update/Solution
#Dharmara - thank you for the gist. It did not work as-is, so I decided to change to async/await and wrap it in try/catch (to hopefully find out why it wasn't working), like so:
try {
let querySnapshot = await db.collection('users').get()
if (querySnapshot.size === 0) {
console.log('No documents to update')
return 'No documents to update'
}
const batches: any[] = [] // hold batches to update at once
querySnapshot.docs.forEach((doc, i) => {
if (i % 500 === 0) {
batches.push(db.batch())
}
const batch = batches[batches.length - 1]
batch.update(doc.ref, { "words.subscription": 0 })
})
await Promise.all(batches.map(batch => batch.commit()))
console.log(`${querySnapshot.size} documents updated`)
return `${querySnapshot.size} documents updated`
}
catch (error) {
console.log(`***ERROR: ${error}`)
return error
}
When I tested this however, it worked. From what I can tell it's the same as the then() way you had in the gist (and from what I had found elsewhere in SO).
If you wanted to put this into an answer I'd gladly mark it as the answer. Your code helped tremendously. Thank you.
The dot notation you use to write a nested field only works when you call update(), not for set(). Luckily update() works for non-existing fields, it only requires that the document already exists.
So for the namespaced API of v8 and before that'd be:
doc.ref.update({
"words.subscription": 0
})
For the modular API for v9 and beyond, it's:
update(doc.ref, {
"words.subscription": 0
})

how to use "where" on a query with entity repository from table relations

I am trying to do a query that with query builder works fine but when I try to do it with entity repository fails.
Anyone can tell me what I am doing wrong?
Query Builder query
const dispatchHeader2 = await this.dispatchHeaderRepository.createQueryBuilder('dh')
.innerJoinAndSelect('dh.driver', 'driver')
.innerJoinAndSelect('dh.vehicle', 'vehicle')
.innerJoinAndSelect('vehicle.transportCompany', 'vtc')
.innerJoinAndSelect('dh.order', 'o')
.where('dh.order_id IN(:...ordersId)', { ordersId })
.andWhere('o.local_origin = :selected_dc', { selected_dc })
.getMany()
Query with Entity Repository
const dispatchHeader = await this.dispatchHeaderRepository.find({
relations: ['driver', 'vehicle', 'vehicle.transportCompany', 'order'],
where: {
order_id: In(ordersId),
order: {local_origin:selected_dc }
}
})
Relation on BD
If i do the query without the
order: {local_origin:selected_dc }
works fine, if i Add that line all fails
Thanks for the help.
img from typeorm Docs
Answering Youba
Dont let me do that
And the query doesnt give me an error, just an empty result. But the query itself dont take any parameters

Unown Way To Change Parameter Inside Mongoose

I am having some issues with saving an object parameter into a mongoose map. My collection looks like this. The collection's name is guildtickets:
{
"_id":"813915771067301888",
"maxopenTickets":"5",
"serverticketnum":"2",
"opentickets": {
"850608478229626891": {
"ticketname":"ticket-0001",
"ticketstatus":"open",
"ticketcreatedby":"843644509324705814"
}
},
"__v":0}
I wish to change the ticketstatus parameter to closed, so the result should be "ticketstatus": "closed". So far I am using:
var queryTicketSchema = await GuildTicketsSchema.findOne({
_id: message.guild.id
});
queryTicketSchema.get(`opentickets`).get(`${message.channel.id}`).ticketstatus = 'closed';
The issue with the code above, is that when logging the collection, the ticketstatus parameter is showed as closed, but while in MongoDB compass, the parameter is still listed as open. Any help is appreciated and more than welcome! Tysm!
Try this:
let ticket = await GuildTicketsSchema.findOne({
_id: message.guild.id
});
ticket.get(`opentickets`).get(`${message.channel.id}`).ticketstatus = 'closed';
await GuildTicketsSchema.findByIdAndUpdate(ticket._id, ticket);

how to get nestjs softremoved products

i'm trying to return softremoved products from db using typeorm, this is code:
async getEndedSalesOfUser(user: User): Promise<Sales[]> {
return await getRepository(Sales)
.createQueryBuilder("sales")
.leftJoin("sales.merchant", "m")
.addSelect(["m.id"])
.where("sales.merchant_id = :id", {id: user.id})
.andWhere("sales.deleted_at != :deleted_at", {deleted_at: null})
.getMany()
}
but in the end, typeorm adds NOT NULL, can anybody tell how to do?
Use .withDeleted() to include non-softdeleted data from your db.

groupBy query with nodejs ravendb client

I am trying to perform groupBy query on ravendb, using nodejs-ravendb-client!
const apmts = await session.query<Appointment>({ collection: "Appointments" })
.statistics(s => (stats = s))
.groupBy("client.name").all();
facing this error on typescript compile
Property 'all' does not exist on type 'IGroupByDocumentQuery<Appointment>'.ts(2339)
Any help here?
Document query's groupBy() method returns an object of type IGroupByDocumentQuery
As you can see it does not have all() method.
You can use selectKey(), selectCount() or selectSum() for aggregation and then chain it with all(). E.g.:
const { GroupByField } = require("ravendb");
const orders = await session.query({ collection: "Orders" })
.groupBy("ShipTo.Country")
.selectKey("ShipTo.Country", "Country")
.selectSum(new GroupByField("Lines[].Quantity", "OrderedQuantity"))
.all();
For more details and examples please refer to official documentation:

Resources