I'm saving data to my db and struggling with updating existing documents. I'd like my app to check if the document already exists and if the info has changed. If the document exists and the info hasn't changed, app skips the document. It's working ok. I'd also want it to update the document in case the data has changed. How can I achieve that?
This is my code responsible for saving the data:
const hash = md5(price + km);
const query = {
hash: hash
},
options = { upsert: true };
Car.findOneAndUpdate(query, options, function(error, result) {
if (!error) {
if (!result) {
result = new Car({
make: make,
model: model,
year: yearInt,
km: kmInt,
price: priceInt,
currency: currency,
link: link,
imageUrls: images,
hash: hash
});
result.save(function(error) {
if (!error) {
console.log('car saved!' + result);
} else {
throw error;
}
});
} else {
console.log('already in db');
}
} else {
console.log(error);
}
});
As you can see, I'm using md5 package to create a hash for every car I'm saving to database. It uses the km and price combination to create the hash. So when the data for "km" or "price" variables changes, the hash also changes. And when it does, I'd like to update the km and/or price data in my db. Should I use the _id instead of hash to find the document?
I also trie something like this to see if the hash had changed but wasn't able to get it right:
if (query.hash != result.hash) {
car.update({
make: make,
model: model,
year: yearInt,
km: kmInt,
price: priceInt,
currency: currency,
link: link,
imageUrls: images,
hash: hash
});
}
I'd be grateful if someone would push me in to the right direction with this.