【发布时间】:2021-11-09 03:26:19
【问题描述】:
所以我想做一个删除回复系统,但我不知道怎么做。你能帮帮我吗? 这是我的桌子 image of my mongodb
我尝试过的代码是,但它不起作用
app.post("/remove-reply", async (req, res) => {
const index = parseInt(req.body.index) - 1
await Posts.findOneAndUpdate({ _id: req.body.id }, [
{
$set: {
"Comments.$[].replies": {
$concatArrays: [
{ $slice: ["$Comments.$[].replies", index] },
{ $slice: ["$Comments.$[].replies", { $add: [1, index] }, { $size: "$Comments.$[].replies" }] }
]
}
}
}
])
res.redirect("/")
})
它给了我这个错误
(node:17376) UnhandledPromiseRejectionWarning: MongoServerError: Invalid $set :: caused by :: FieldPath field names may not start with '$'.
at MessageStream.messageHandler (C:\Users\The.Peerapon\Desktop\programming\Express-app\node_modules\mongodb\lib\cmap\connection.js:467:30)
at MessageStream.emit (events.js:400:28)
at processIncomingData (C:\Users\The.Peerapon\Desktop\programming\Express-app\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
at MessageStream._write (C:\Users\The.Peerapon\Desktop\programming\Express-app\node_modules\mongodb\lib\cmap\message_stream.js:28:9)
at writeOrBuffer (internal/streams/writable.js:358:12)
at MessageStream.Writable.write (internal/streams/writable.js:303:10)
at TLSSocket.ondata (internal/streams/readable.js:731:22)
at TLSSocket.emit (events.js:400:28)
at addChunk (internal/streams/readable.js:293:12)
at readableAddChunk (internal/streams/readable.js:267:9)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:17376) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:17376) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
我的目标是在回复时单击删除按钮以按索引将其删除。
【问题讨论】:
-
已编辑请帮忙
-
现在好多了。如果您可以包含示例数据集和预期输出,那就更好了:) Mongoplayground 是共享 mongodb 可重现示例的便捷工具之一。
-
我的预期输出是通过索引删除帖子中评论中的回复
-
我认为我们仍然需要一些澄清,因为
Comments也是一个数组。你的意思是会给你2个索引,一个给Comments,一个给replies,这样你就可以通过Comments.x.replies.y删除replies中的元素?正如我所说,具体的预期输出将有助于社区了解需求。
标签: javascript html mongodb