0

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?

6
  • 2
    May be just a typo, but GroupSchema uses friends and your code uses friend. Commented Jan 12, 2014 at 22:01
  • That was a typo - I fixed it. Same issue Commented Jan 12, 2014 at 22:27
  • The code looks fine, so if the last element of friends gets updated, then that element must match your query. Commented Jan 12, 2014 at 23:08
  • It's always the last element. Regardless of what I specify Commented Jan 13, 2014 at 1:53
  • Can you update your question to include sample docs that reproduce the problem? Commented Jan 13, 2014 at 1:58

1 Answer 1

2

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

Comments

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.