Friday 26 October 2018

Mongoose: use UpdateMany instead of InsertMany?

This seems like it should be a very simple process, and probably is, but I can't seem to find the best way implement this.I need the ability to upload an array of "Product" objects to mLab with Mongoose. First I will loop through the uploaded items to validate them, then I need to insert/update them. Here is how I'm inserting them now.Sample Products:[{"sku": "bar32","name": "Test 1","owner": "5bcd137a7cc407380d5a0802"},{"sku": "foo64","name": "Test 2","owner": "5bcd2d669637b63f06e32f9b"}]​Validate and upload:let accepted = [];products.forEach(function(product) {if (validate(product)) accepted.push(product);});Product.insertMany(accepted, function(err, docs) {...});​This works great, but the next time a product list is given I need to be able to insert any new products, update any products that already exist (if SKU exists) and were uploaded again, and don't touch any products that exist in DB but weren't uploaded again.I was hoping I could actually just replace my originalProduct.insertMany(accepted, function(err, docs)with:Product.updateMany({upsert: true}, accepted, function(err, docs)This way on the first upload none would exist so they would just be upserted, then on subsequent uploads I could hit the same function and it would update any that exist and upsert the rest. However this did not seem to work. It may be my syntax that's incorrect but I couldn't find any examples doing it this way. Most examples use BulkWrite but this seems like something UpdateMany should be able to handle.Any advice?

Submitted October 26, 2018 at 07:13PM by Wishwatch

No comments:

Post a Comment