简体   繁体   English

从对象数组中的对象中删除属性 mongoose

[英]remove a property from an object in an array of objects mongoose

I have a MongoDB document like this:我有一个这样的 MongoDB 文档:

{
  "_id": ObjectId("5589044a7019e802d3e9dbc5"),
  groups:[
    {
      _id: 5a3326d01b2213894672fdd0,
      group_id: '13239517',
      thread_id: 'f32940da-12-15-01-9325790',
      Last_post_id: '981206845'
    }
  ]
}

I've tried a variation of $set and $unset using:我尝试了$set$unset的变体,使用:

User.findOneAndUpdate({userId}, {groups:{$set: {thread_id: ''}}}, {new: true})

when I tried multiple variations of the above code I keep on getting groups where the affected object is only left with an id.当我尝试上述代码的多种变体时,我继续获取受影响对象仅留下一个 id 的组。

[
  { _id: 5a3326d41b2213894672fdd1 },
  {
    _id: 5a332a81479a728ebe4226e5,
    group_id: '13239517',
    thread_id: 'f32940da-12-15-01-9325790',
    Last_post_id: '981206845'
  }
]

I've also tried looping over the array of groups removing the key using reduce then just trying to set the groups to this new values like and that didn't work either.我还尝试循环使用 reduce 删除键的组数组,然后尝试将组设置为这个新值,例如,这也不起作用。

let groups = groups.reduce((prev, ele)=>{
  // group_id is passed in as an argument
  if(ele.group_id === group_id){
    let chatThread = ele.thread_id
    delete ele.thread_id
    console.log(ele)
    return chatThread
  } else {
    return prev
  }
}, false)
User.findOneAndUpdate({userId}, {groups}, {new: true})

this just doesn't do anything.这只是没有做任何事情。

My intended result would be where thread_id is gone我的预期结果将是thread_id消失的地方

groups:[
  {
    _id: 5a3326d01b2213894672fdd0,
    group_id: '13239517',
    Last_post_id: '981206845'
  }
]

Although similar to link1 and link2 both of those solutions either don't change anything when saved or remove all properties other than _id.尽管与link1link2类似,这两个解决方案在保存或删除_id 以外的所有属性时都不会更改任何内容。

this did work for me.这对我有用。 looks like reduce and map when using delete keyword will not affect the original array I assumed it would since i thought it was passed by reference.使用 delete 关键字时看起来像 reduce 和 map 不会影响我认为它会影响的原始数组,因为我认为它是通过引用传递的。

User.findOne({userId}, async(err, user)=>{
            let new_groups = user.groups.map(ele=>{
              // group id is passed as an argument
              if(ele.group_id === group_id){
                return {
                  group_id:ele.group_id,
                  _id: ele._id,
                  Last_post_id: ele.Last_post_id
                }
              }
              return ele
            })
            var updateUserGroups = await User.findOneAndUpdate({userId}, {groups: new_groups}, {new: true})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM