Shamoon
Shamoon

Reputation: 43491

How to update a specific array element with Mongoose?

My Schema looks like:

var FriendSchema = new Schema({
  friend_id: String,
  gender: String,
  meta: {
    address: String,
    amount: Number
  }
}, { _id : false });

var GroupSchema = new Schema({
  unique_id: {
    type: Number,
    required: true,
    unique: true
  },
  friends: [FriendSchema]
});

So a Group contains an array of friends and a friend has a meta with some information in it. I want to update a specific friend in the group that matches certain criteria. Here's what I've tried:

groupQuery = {unique_id: someId, 'friends.friend_id': friendNum, 'friends.gender': gender}
groupUpdate = {$set: {'friends.$.meta.address': myAddress, 'friends.$.meta.amount': debt}}

Group.update groupQuery, groupUpdate, (err) ->

What happens is the last friend in the group gets updated. Not the specific one that I want. What am I doing wrong?

Upvotes: 0

Views: 280

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

To get the $ in your update to identify the element that matches both properties in your query, you need to use $elemMatch in your query object:

groupQuery = {
    unique_id: someId, 
    friends: {$elemMatch: {friend_id: friendNum, gender: gender}}
}

Upvotes: 2

Related Questions