How to add to field if id already exists #4855
Answered
by
ganigeorgiev
gaganbiswas
asked this question in
Q&A
-
I have a routerAdd("POST", "/stock/add", (c) => {
const info = $apis.requestInfo(c);
const { data } = info.data;
const stock_collection = $app.dao().findCollectionByNameOrId("stock");
const vstock_collection = $app
.dao()
.findCollectionByNameOrId("virtual_stock");
$app.dao().runInTransaction((txDao) => {
for (let item of data) {
const stock_record = new Record(stock_collection);
const vstock_record = new Record(vstock_collection);
const stock_form = new RecordUpsertForm($app, stock_record);
stock_form.setDao(txDao); // use the transaction dao for the db operations
stock_form.loadData(item);
stock_form.submit();
const vstock_form = new RecordUpsertForm($app, vstock_record);
vstock_form.setDao(txDao); // use the transaction dao for the db operations
vstock_form.loadData(item);
vstock_form.submit();
// verify that the inserted record can be accessed by the current request client, otherwise rollback
if (
!txDao.canAccessRecord(
stock_record,
info,
stock_collection.createRule
) &&
!txDao.canAccessRecord(
vstock_record,
info,
vstock_collection.createRule
)
) {
throw new ForbiddenError("The operation is not allowed.");
}
}
});
return c.json(200, { status: 1 });
}); But, I also wanna check if my stock & virtual stock already have the product and if it does then I just wanna update the quantity for the same. My stock & virtual_stock has the same model: Side Note: The data that I am sending is in the form of {product: string, quantity: number}[] |
Beta Was this translation helpful? Give feedback.
Answered by
ganigeorgiev
May 2, 2024
Replies: 1 comment 9 replies
-
You can call let stock_record;
try {
stock_record = txDao.findRecordById(stock_collection.id, item.id);
} catch {
stock_record = new Record(stock_collection);
}
let vstock_record;
try {
vstock_record = txDao.findRecordById(vstock_collection.id, item.id);
} catch {
vstock_record = new Record(vstock_collection);
} |
Beta Was this translation helpful? Give feedback.
9 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
On second read and based on your side-note, you want to check for
stock_record
/vstock_record
based on the "product" field and not on the "id". In this case you can replacefindRecordById
in the above withfindFirstRecordByData(yourCollecitonNameOrId, "product", item.product)
(assuming that theproduct
field is unique).