0

with the following mongo object,

how would I findById of a user whose _id is '590ac6b7663350948be1c085' to then find in their friends array an object whose id is '590ac6ac663350948be1c083' and then set its status property to 1?

_id: 590ac6b7663350948be1c085,
username: 'someusername',
friends:
[{ 
  id: 590ac6ac663350948be1c083,
  status: 0,
  _id: 590ace171aa0aeb58f798466 
}]

I've tried

User.findOne({'_id': '590ac6b7663350948be1c085'}).then(user => {
    let friend = user.friend.id('590ac6ac663350948be1c083');
    friend.status = 1;
    return user.save();
});

for now the schema is rather simple

var UserSchema = new Schema({
  username   : String,
 friends    : 
  [{ 
    id: { type: Schema.Types.ObjectId, ref: 'User'}, 
    status: Number 
  }]
});

or is a better approach to find the _id of that particular friend object and update that then? if so, how would I do that as this query returns the entire user object

User
.findOne({ 'friends._id' : '590ace171aa0aeb58f798466' })
.then(user => {
console.log(user)
totalnoob
  • 2,521
  • 8
  • 35
  • 69
  • As the answer in the marked dupe implies, your update operation is atomic `User.findOneAndUpdate({ '_id': '590ac6b7663350948be1c085', 'friends.id': '590ac6ac663350948be1c083' }, { '$set': { 'friends.$.status': 1 } }, { 'new': true }).exec().then(user => console.log(user));` – chridam May 04 '17 at 14:12
  • thanks, what's the $ in the dot notation? – totalnoob May 04 '17 at 14:33
  • It's called the [`positional` **`$`** `operator`](https://docs.mongodb.com/manual/reference/operator/update/positional/) and it identifies an element in an array to update without explicitly specifying the position of the element in the array. – chridam May 04 '17 at 14:36

0 Answers0