gpt4 book ai didi

node.js - 从 mongodb 数组中提取元素

转载 作者:太空宇宙 更新时间:2023-11-04 00:08:35 25 4
gpt4 key购买 nike

我有一个问题,我在这个问题上浪费了比应有的时间更多的时间,而且我似乎不明白我做错了什么。

我在 MongoDB 中有以下文档:

{
"personal": {
...
},
"preferences": {
....
},
"_id": "5b2efdad564191054807c2b1",
"pets": [],
"conversations": [
{
"unread": 1,
"participants": [
{
"_id": "5b2efdcd564191054807c2b2",
"name": "Mighty Jules"
}
],
"messages": [
{
"sender": "self",
"timestamp": "2018-06-24T12:29:50.656Z",
"_id": "5b2f8ebede342a12a8dcc9d2",
"text": "..."
},
{
"sender": "self",
"timestamp": "2018-06-24T12:29:58.022Z",
"_id": "5b2f8ec6de342a12a8dcc9d8",
"text": "..."
},
{
"sender": "5b2efdcd564191054807c2b2",
"timestamp": "2018-06-24T12:30:27.562Z",
"_id": "5b2f8ee3de342a12a8dcc9e5",
"text": "..."
},
{
"sender": "self",
"timestamp": "2018-06-24T12:32:48.034Z",
"_id": "5b2f8f70d3a83e25bc1abbb2",
"text": "..."
},
{
"sender": "self",
"timestamp": "2018-06-24T12:36:20.027Z",
"_id": "5b2f9044d4137828283c5a60",
"text": "..."
},
{
"sender": "5b2efdcd564191054807c2b2",
"timestamp": "2018-06-24T12:37:39.965Z",
"_id": "5b2f90939b4b2a4af8cf50db",
"text": "..."
}
],
"last_message": "2018-06-24T12:37:39.965Z",
"_id": "5b2efdcd564191054807c2b2"
},
{
"unread": 1,
"participants": [
{
"_id": "5b300ff657957c1aa0ed0576",
"name": "Super Frank"
}
],
"messages": [
{
"sender": "5b300ff657957c1aa0ed0576",
"timestamp": "2018-06-24T21:42:49.392Z",
"_id": "5b30105957957c1aa0ed0583",
"text": "..."
}
],
"last_message": "2018-06-24T21:42:49.392Z",
"_id": "5b300ff657957c1aa0ed0576"
}
],
"created_date": "2018-06-24T02:10:53.314Z",
"lastLogin_date": "2018-06-24T02:10:53.314Z",
"lastUpdate_date": "2018-06-25T02:09:53.281Z",
"__v": 0
}

我正在尝试使用 Mongoose 删除几条消息:

const user = await User.findOneAndUpdate(
{
_id: mongoose.Types.ObjectId("5b2efdad564191054807c2b1"), //Which is the one that doc
"conversations._id": mongoose.Types.ObjectId("5b2efdcd564191054807c2b2")
},
{
$pull: {
"conversations.$.messages": {
$in: [
{ _id: mongoose.Types.ObjectId("5b2f9044d4137828283c5a60") },
{ _id: mongoose.Types.ObjectId("5b2f90939b4b2a4af8cf50db") }
]
}
}
},
{
new: true,
projection: {
conversations: 1
}
}
);

在响应中我得到了相同的结果,没有删除任何内容,也没有收到任何错误。

最佳答案

首先,示例文档中的_id是字符串,而不是ObjectId。其次,$pull 语法是错误的。请阅读https://docs.mongodb.com/manual/reference/operator/update/pull/#remove-items-from-an-array-of-documents 。应该是:

{
$pull: {
"conversations.$.messages": {
"_id": {
"$in": ["5b2f9044d4137828283c5a60", "5b2f90939b4b2a4af8cf50db"]
}
}
}
}

如果您想要的话,它将从第一个匹配对话中提取消息。如果您想从所有匹配对话中删除消息,则需要使用$[]相反:“conversations.$[].messages”

关于node.js - 从 mongodb 数组中提取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51015586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com