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 } 

Add data to context_task.task using the following query

 task.update({"_id": req.body.id_project}, {$push: {'context_task': {'task': req.body.input_task,'status': false}}}, function (err) { if (err) return next(err); var body = req.body.id_project+","+req.body.input_task; res.status(200).send(body); }); 

Tell me, how can I get the context_task._id of a new record after insertion? I tried to send the second parameter to the callback, but it returns only the status of the request.

 function (err, doc) { if (err) return next(err); console.log(doc); //output -> { n: 1, nModified: 1, ok: 1 } res.status(200).send(); }); 
  • And the update method, by chance, does not return the id of the record? - Vladimir Parfenov
  • @VladimirParfenov On the docks, it says that the method returns a WriteResult - an object containing the operation status. - Vova Zhuravlev

2 answers 2

The issue was resolved as follows: The request to add a new record was rewritten as suggested by Sergey, and the ID of the new record was obtained using

  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(); }); 
     Task.findOneAndUpdate({'...': ...}, {upsert: true}, function (err, doc) { if (err) { console.log('Error in Saving task: ' + err); throw err; } console.log(doc); }); 
    • It is desirable to name the model object with a capital letter on the docks of Mongi. - larrymacbarry
    • Thanks, in this case, the entire dock is returned entirely but without a new record, I need the id of the new object in the array. console.log (doc) output is possible; occur before the record, because everything goes correctly to the base, tell me how you can fix it or which way to dig? - Vova Zhuravlyov
    • stackoverflow.com/questions/32811510/… Use the {new: true} option - larrymacbarry
    • I apologize for the stupid question, but I still do not understand how to return the _id of the new record, I can get the entire array of results from this query, and then through another query, choose _id or is it easier to do that? I will be glad to any kick :) - Vova Zhuravlyov
    • doc.context_task._id by logic, as well as to a regular key in an array, it is also possible through ["_id"] - larrymacbarry