1

I was able to successfully use a { key: value } structure for the ...

    const findOneAndUpdateUpdate = { 
      $set: ratingsHistoryObject,
      $inc: ratingIncrementObject
    }

... part in the below code. However, for the ..

    const findOneAndUpdateFilter = {
      'userId': userIds[0],
      matchIdPath: { $exists: false },
    }

... part, no curly braces are to be used. It should be something like: ...

    const findOneAndUpdateFilter = {
      'userId': userIds[0],
      "ratingsHistory.squash.60003e9267684effa0f56ffb": { $exists: false },
    }

... but then with a dynamic matchIdPath. How can I realize this when the { key: value } method does not work here because there are no curly braces to start matchIdPath with?

Full code extract:

    // Other code

    matchesData.forEach(async match => {

    // Other code

    const matchIdPath = `ratingsHistory.${match.matchType}.${match._id}`

    
    var ratingsHistoryObject = {}
    var ratingsHistoryObjectKey = 'ratingsHistory.' + match.matchType + '.' + match._id
    var ratingsHistoryObjectValue = difference_result
    ratingsHistoryObject[ratingsHistoryObjectKey] = ratingsHistoryObjectValue
    
    var ratingIncrementObject = {}
    var ratingIncrementObjectKey = 'ratings.' + match.matchType
    var ratingIncrementObjectValue = difference_result
    ratingIncrementObject[ratingIncrementObjectKey] = ratingIncrementObjectValue
    

    const findOneAndUpdateFilter = {
      'userId': userIds[0],
      matchIdPath: { $exists: false },
    }
    
    
    const findOneAndUpdateUpdate = { 
      $set: ratingsHistoryObject,
      $inc: ratingIncrementObject
    }

    const usersResult = await usersCollection.findOneAndUpdate(findOneAndUpdateFilter, findOneAndUpdateUpdate);
turivishal
  • 34,368
  • 7
  • 36
  • 59
beyondtdr
  • 411
  • 6
  • 17

1 Answers1

1

You can use the computed property name syntax:

const findOneAndUpdateFilter = {
    'userId': userIds[0],
    [matchIdPath]: { $exists: false },
}

Example:

let key = "ratingsHistory.squash.60003e9267684effa0f56ffb";

let obj = { [key]: { $exists: false } };

console.log(obj);
mickl
  • 48,568
  • 9
  • 60
  • 89