Node JS 从数组中删除特定对象(猫鼬)
Posted
技术标签:
【中文标题】Node JS 从数组中删除特定对象(猫鼬)【英文标题】:Node JS remove a specific object from array (mongoose) 【发布时间】:2021-12-18 21:39:30 【问题描述】:我有一个对象数组 - 列表[];和一个对象 - obj;
这是列表数组:
_id: new ObjectId("61840c5ce237f22a1c7a1ac7"),
name: 'list1',
content: [ 'aaaa' ],
description: 'aa',
tags: [],
lastmodified: 1,
__v: 0
,
_id: new ObjectId("61840def80a88d1b2ffce400"),
name: 'list',
content: [ 'list!' ],
description: 'test',
tags: [],
__v: 0
这是 obj 对象:
_id: new ObjectId("61840def80a88d1b2ffce400"),
name: 'list',
content: [ 'list!' ],
description: 'test',
tags: [],
__v: 0
简单问题:如何从“列表”中删除对象,类似于“obj”之一
【问题讨论】:
这能回答你的问题吗? How to remove Object from array using mongoose 【参考方案1】:使用某种过滤...这是一个想法。
items = [
_id: new ObjectId("61840c5ce237f22a1c7a1ac7"),
name: 'list1',
content: [ 'aaaa' ],
description: 'aa',
tags: [],
lastmodified: 1,
__v: 0
,
_id: new ObjectId("61840def80a88d1b2ffce400"),
name: 'list',
content: [ 'list!' ],
description: 'test',
tags: [],
__v: 0
]
removeID = "61840def80a88d1b2ffce400"
items = [item for item in items if item['id'] != removeID]
【讨论】:
【参考方案2】:您可以使用 javascript Array.filter()
方法从列表中排除目标对象:
const list = [
_id: new ObjectId("61840c5ce237f22a1c7a1ac7"),
name: 'list1',
content: [ 'aaaa' ],
description: 'aa',
tags: [],
lastmodified: 1,
__v: 0
,
_id: new ObjectId("61840def80a88d1b2ffce400"),
name: 'list',
content: [ 'list!' ],
description: 'test',
tags: [],
__v: 0
];
const targetObj =
_id: new ObjectId("61840def80a88d1b2ffce400"),
name: 'list',
content: [ 'list!' ],
description: 'test',
tags: [],
__v: 0
;
const filteredList = list.filter((element) => element._id !== targetObj._id);
【讨论】:
以上是关于Node JS 从数组中删除特定对象(猫鼬)的主要内容,如果未能解决你的问题,请参考以下文章