как удалить массив элементов в mongodb - PullRequest
0 голосов
/ 30 мая 2019

Я пытаюсь удалить массив элементов, но он вообще не работает ..

в схеме

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"
    ]
}

Массив элементов не удаляется .. в нем отображаются все детали коллекции.как удалить элементы из mongodb, используя $ Pull или любой другой.

Ответы [ 2 ]

0 голосов
/ 30 мая 2019

Вы забыли запрос на совпадение, а также функции БД асинхронные , поэтому вам нужно будет ждать , чтобы завершить операцию обновления, прежде чем запрашивать, чтобы проверить, изменилась ли БД, это можетбыть сделано с асинхронными функциями

// 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);
    }
});
0 голосов
/ 30 мая 2019

Попробуйте, как показано ниже:

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 update function

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...