V
V
Vladimir2017-04-20 10:37:42
JavaScript
Vladimir, 2017-04-20 10:37:42

How to get the ID of a new entry in MongoDB?

There is such a document structure in MongoDB

{
"_id" : ObjectId("58f7d556aa52ce456672a67e"),
"created" : ISODate("2017-04-19T21:23:34.315Z"),
"context_task" : [
    {
        "task" : "напишем немного текста ",
        "status" : false,
        "_id" : ObjectId("58f7d559aa52ce456672a67f")
    }
],
"head" : {
    "userID" : "58f48037fc894e19a3f7b81b",
    "head_task" : "пробный забег "
},
"__v" : 0
}

I add data to context_task.task with the following query
task.findOneAndUpdate({"_id": req.body.id_project},
            {$push: {'context_task': {'task': req.body.input_task,'status': false}}},{new: true},
            function (err, doc) {
                if (err) return next(err);
                var body = req.body.id_project+","+req.body.input_task;
                console.log(doc);
                res.status(200).send(body);
            });

Tell me, how can I get the context_task._id of a new record after inserting? In this case, the entire document is returned.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2017-04-20
@zhuravlev125

Maybe someone will come in handy. The issue was resolved as follows.

Task.findOneAndUpdate({"_id": req.body.id_project},
            {$push: {'context_task': {'task': req.body.input_task,'status': false}}},{new: true},
            function (err, doc) {
                if (err) return next(err);
                console.log(doc.context_task[doc.context_task.length-1]._id);//получаем ID новой записи 
                res.status(200).send();
            });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question