簡體   English   中英

MongoDB:如何按索引刪除嵌套對象?

[英]MongoDB: How do I delete nested object by index?

所以我想做一個刪除回復系統,但我不知道該怎么做。 你能幫幫我嗎? 這是我的 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.

我的目標是在回復時單擊刪除按鈕以按索引刪除它。

對於每個評論\\回復,將其索引保存在數據庫中並將其用作一種 id。 然后,當有人想要刪除評論時,您可以執行以下操作:

app
  .post('/remove-reply', async (req, res) => {
    const postId = req.body.id;
    const commentIndex = parseInt(req.body.commentIndex) - 1;
    const replyId = req.body.replyIndex;
    await Posts.findOneAndUpdate({
      _id: postId
    }, {
      $pull: {
        [`Comments.${ commentIndex }.replies`]: {
          _id: replyId 
        }
      }
    });
    res.redirect('/');

  });

因此,當用戶單擊要刪除的回復時,您應該擁有查找要刪除的確切回復所需的所有 3 個字段。

您還可以為每個項目保存一個自動生成的唯一 id 以用作標識符\\索引,因為在此用例中,我們將其視為集合而不是數組。 由於刪除注釋后,索引不再與底層數組對齊,因此維護起來可能會更容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM