所以我想做一個洗掉回復系統,但我不知道該怎么做。你能幫幫我嗎?這是我的 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.
我的目標是在回復時單擊洗掉按鈕以按索引洗掉它。
uj5u.com熱心網友回復:
對于每個評論\回復,將其索引保存在資料庫中并將其用作一種 id。然后,當有人想要洗掉評論時,您可以執行以下操作:
async function deleteReplyByIndex(postId, commentIndex, replyIndex) {
return await Posts.update({
id: postId
},
{
$pull: {
`Comments.${ commentIndex }.replies`: {
index: replyIndex
}
}
});
}
因此,當用戶單擊要洗掉的回復時,您應該擁有查找要洗掉的確切回復所需的全部 3 個欄位。
您還可以為每個專案保存一個自動生成的唯一 id 以用作識別符號\索引,因為在此用例中,我們將其視為集合而不是陣列。由于洗掉注釋后,索引不再與底層陣列對齊,因此維護起來可能會更容易。
希望這有幫助!如果對您有幫助,請選擇答案!
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/353762.html
