I am working on a such application where the first user creates records for offline use. and then after doing his work in the evening, he tries to sync the data to the cloud/server database.
I have coded it but the issue we are facing is that during this perform a sudden electricity outage occurs or a crash or anything can happen so We have to handle that case.
I have tried activating flight mode or stopping the project while syncing but the issue we have found is that total products = 1000 – online db = 500 products added – offline db = 499 products status updated.
We are facing this issue that is one product always left behind when we manually close the server in node js and express js.
how to fix this issue?
const index = async (req, res) => {
const client = new MongoClient(mongoURI);
try {
await client.connect();
const db = client.db(dbName);
const productsCollection = db.collection(collectionName);
// Fetch products to be synced
const updatedProductsArray = await Product.findAll({
where: { isSynced: [1, 3] }, // Fetching records with isSynced status 1 (new) or 3 (updated)
});
if (updatedProductsArray.length > 0) {
for (const product of updatedProductsArray) {
const { isSynced, ...productData } = product.dataValues;
try {
if (isSynced === 3) {
// Update existing document
await productsCollection.updateOne(
{ product_id: productData.product_id },
{ $set: { ...productData, isSynced: 2 } },
{ upsert: true }
);
} else {
// Insert new document
await productsCollection.insertOne({ ...productData, isSynced: 2 });
}
// Update local database to mark the product as synced
await Product.update(
{ isSynced: 2 },
{ where: { product_id: productData.product_id } }
);
} catch (err) {
console.error(`Error syncing product ID ${productData.product_id}:`, err);
continue; // Skip to the next product
}
}
}
res.json({ status: 1, msg: "Data Sync Successfully !!!" });
} catch (error) {
console.error("Error syncing data:", error);
res.status(500).json({ error: "Error syncing data" });
} finally {
client.close();
}
};