簡體   English   中英

我如何刪除mongodb中的元素數組

[英]how do i remove array of elements in mongodb

我正在嘗試刪除元素數組但它根本不工作..

在架構中

var connectedUsers = Schema({
  fruits: { type: Array },
  vegetables: { type: Array }
})
var connectedusers = mongoose.model("connectedusers", connectedUsers) 

節點js路由文件

router.post('/connectedusers', function(req,res) {
connection.connectedusers.update(
        { $pull: { fruits: { $in: [ "apples", "oranges" ] }, vegetables: "carrots" } },
        { multi: true }
    )
    connection.connectedusers.find({}, function (err, docs) {
        if (err) throw err;
        res.json({
            docs: docs
        })
    })
});

在mongodb集合

{
    "_id": {
        "$oid": "5cef68f690a42ba057760e98"
    },
    "__v": 0,
    "connectArray": [
        "vinay",
        "vinay1"
    ],
    "fruits": [
        "apples",
        "pears",
        "oranges",
        "grapes",
        "bananas"
    ],
    "vegetables": [
        "carrots",
        "celery",
        "squash",
        "carrots"
    ]
}

元素數組未刪除..它顯示所有集合詳細信息。 如何使用$ Pull或任何其他方法從mongodb中刪除元素。

請嘗試以下方式:

router.post('/connectedusers', function(req,res) {
connection.connectedusers.update(
        {},                   //  Missing query part
        { 
           $pull: { 
                 fruits: { $in: [ "apples", "oranges" ] }, 
                 vegetables: "carrots" 
           } 
        },
        { multi: true }
    )
    connection.connectedusers.find({}, function (err, docs) {
        if (err) throw err;
        res.json({
            docs: docs
        })
    })
});

您的查詢工作正常我在我的最后嘗試過。 您缺少MongoDB 更新功能的查詢部分

您忘記了匹配查詢,db函數也是異步的,因此您需要等待更新操作完成,然后再查詢以檢查db是否已更改,這可以通過異步函數完成

// change callback to an async arrow function
router.post('/connectedusers', async (req, res) => {
    try {
        // wait for this operation to complete before continuing
        await connection.connectedusers.update(
            {},
            { $pull: { fruits: { $in: [ "apples", "oranges" ] }, vegetables: "carrots" } },
            { multi: true }
        );
        // update complete now wait for the find query
        const docs = await connection.connectedusers.find({});
        // no errors, send docs.
        // if the variable name is the same as your field
        // that you want to send in the object you can just
        // pass that variable directly
        res.json({ docs });
    // catches errors from both update and find operations
    } catch (err) {
        // set the status code and send the error
        res.status(/* error status */).json(err);
    }
});

暫無
暫無

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

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