我有一个像这样的MongoDB文档:
{
"_id": ObjectId("5589044a7019e802d3e9dbc5"),
groups:[{
_id: 5a3326d01b2213894672fdd0,
group_id: '13239517',
thread_id: 'f32940da-12-15-01-9325790',
Last_post_id: '981206845'}]
}
我尝试使用$set
和$unset
的变体:
User.findOneAndUpdate({userId}, {groups:{$set: {thread_id: ''}}}, {new: true})
当我尝试上述代码的多种变体时,我继续获取受影响对象只留下id的组。
[ { _id: 5a3326d41b2213894672fdd1 },
{ _id: 5a332a81479a728ebe4226e5,
group_id: '13239517',
thread_id: 'f32940da-12-15-01-9325790',
Last_post_id: '981206845' } ]
我还试图在使用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})
这只是没有做任何事情。
我的预期结果将是thread_id
消失的地方
groups:[{
_id: 5a3326d01b2213894672fdd0,
group_id: '13239517',
Last_post_id: '981206845'}]
答案 0 :(得分:0)
这对我有用。使用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})