0

I have a collection of documents like following schema

{
    _id: ObjectId('xxxxxxxxxxxxxxxxxxx'),
    name: "abc",
    value: 1.11,
    otherField1: "def",
    otherField2: "ghi"
},
{
    _id: ObjectId('xxxxxxxxxxxxxxxxxxx'),
    name: "def",
    value: 2.15,
    otherField1: "jkl",
    otherField2: "abc"
}

I am calling an API which gives me result like this

{
    name: "abc",
    newValue: 3.12
},
{
    name: "def",
    newValue: 5.16
}

Now I have to update all documents with their new values by matching name field. One way is to run a loop on result and use mongoose's findOneAndUpdate function. Is there any other way where I don't need to run a loop and can update all documents using only single query.

Note: name field is unique in collection

Please also note that I am updating documents' "value" field using "newValue" field from the result of the API

Dhruv Pahuja
  • 105
  • 1
  • 10
  • Can you show your query please? – styopdev Jul 16 '17 at 07:25
  • function updateRecords(req, res) { req.body.forEach(function(element, index) { MyModel.findOneAndUpdate({"name": element.name}, {"value": element.newValue}) .then(function() { console.log("Record Updated"); }) .catch(function(err) { console.log(err); }); }); return res.status(200).send({success: true, data: "Records Updated"}); } – Dhruv Pahuja Jul 16 '17 at 07:57

0 Answers0