A
A
Adel Khalitov2019-02-27 12:58:54
MongoDB
Adel Khalitov, 2019-02-27 12:58:54

How to change a specific field of an element in an array in mongodb?

{
    "_id": {
        "$oid": "5c738e04fe875703f8e05d82"
    },
    "contactPhones": [
        "+7"
    ],
    "leadId": "e527066e-ba54-78d1-dff8-a271de67cce1",
    "leadStatus": "attemptCommunicateLPR",
    "firmName": "Э",
    "contactName": "",
    "position": "",
    "contactEmail": "rou",
    "address": "Дос",
    "lprsName": "Руст",
    "comments": [],
    "tasks": [
        {
            "_id": {
                "$oid": "5c738e04fe875703f8e05d84"
            },
            "status": "started",
            "action": "call",
            "description": "У них ",
            "createdDate": "2019-02-25T06:34:27.971Z",
            "deadLineDate": "2019-02-26T06:30:14.000Z"
        }
    ],
    "link2gis": "https://2gis.ru,
    "createdDate": "2019-02-25T06:34:27.971Z",
    "__v": 0
}

I need to change an element of the tasks array with a specific _id.
I am trying to do it this way:
app.post('/changeStatus', function(req, res) {
    db.Lead.findOneAndUpdate({leadId: req.body.leadId},
        {$set: {'tasks.$[element].status' : 'finished' } },
        { arrayFilters: [ { "element": { _id: req.body.changedTask._id } } ] }
        ).then(data => {
            console.log(data);
        }, err => {
            console.log(err);
        })
});

The data is sent in the following format:
this.myHttp.postHTTP('http://localhost:3000/changeStatus', {leadId: this.Lead.leadId, changedTask: task} )

Where in the task is the object that contains the _id key
As a result, the server does not change my object in the database and returns the initial version. What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Adel Khalitov, 2019-02-27
@SaveLolliPoP

router.post('/changeStatus', function(req, res) {
    db.Lead.findOneAndUpdate({'leadId': req.body.leadId, 'tasks._id': req.body.changedTask._id},
        {$set: {'tasks.$.status' : 'finished' } },
        ).then(data => {
            console.log(data);
        }, err => {
            console.log(err);
        })
});

This is how it should look

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question