1

I've seen example like this or this SO question where we can easily use the positionnal $ operator to update an object in an array.

I'm trying to do the same thig but I must use an object sub-property.

Exemple:

// Data model:
UserSchema = new Schema({
permissionsPerOrganization: [{
    organization: {
        type: ObjectId,
        ref: 'Organization'
    },
    role: {
        type: ObjectId,
        ref: 'Role'
    }
}],

I must update Role in permissionsPerOrganization with an exact _id.

Here is what I have:

this.activeSchema.findByIdAndUpdate(
    { _id: user._id, 'permissionsPerOrganization.organization._id': org._id },
    { 'permissionsPerOrganization.$.role': roleId },
    {
        new: true
    })

I also have tried with the new $[identifier] syntax which seem made for that kind of use case but it fails...

Have you got a clue please ?

Ashh
  • 44,693
  • 14
  • 105
  • 132
TOPKAT
  • 6,667
  • 2
  • 44
  • 72

1 Answers1

2

You can try with arrayFilters in following way

db.collection.update(
  { "_id": user._id }, 
  { "$set": { "permissionsPerOrganization.$[array].role": roleId  }},
  { "arrayFilters": [{ "array.organization": org._id }], new: true }
)
Ashh
  • 44,693
  • 14
  • 105
  • 132