更新猫鼬数组

时间:2018-08-31 19:53:12

标签: arrays mongoose

我有一个这样的模式

first_name      : String,
other_names     : String,
last_name       : String,
title           : String,   
friends     :[{
    _id             : String,
    friend_type     : String,//e.g. best, school
    comment         : String,//the school where this email is also linked to
    nickname        : String
}]

我在昵称中有一些数据,但是其他字段我没有任何信息 我想用friend_type更新朋友数组,当前数据库中不存在这个数组。 这些是我到目前为止尝试过的。

PersonModel.update({
    _id: 'users id is here',
    'friends[0]._id': friend_id,
  }, {
    $set: {
      'friends[0].friend_type': 'office'
    }
  },
  /**
   Other options that I tried arebelow
  **************/
  //{$addToSet: { 'friends[0].friend_type': 'office'} },
  //{$push: { 'friends[0].friend_type': 'office'} },
  {
    multi: true
  },
  function(err, friendDetail) {
  });

请问我该怎么办

1 个答案:

答案 0 :(得分:1)

尝试:

 {$set: { 'friends.0.friend_type': 'office'} }

因为您不想更新主对象,而是要更新其子元素

相关问题