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 ?

1 Answer 1

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 }
)
Sign up to request clarification or add additional context in comments.

3 Comments

Wow !! Thank you, I think I was misunderstanding the concept of object._id
Sorry, spoke a bit too quick...this doesn't update nothing in my collection but doesn't throw error...
You need to cast your id to ObjectId then it will definitely work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.