Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return updated collection with Mongoose

I work with nodejs/express/mongoose/angularjs. I'd like to update a collection named Lists which has several properties, one of which is an array of items. In the following code, I'm pushing a new task items in the items array. Everything works fine, however the update function does not sends back the updated collection, then I must perform another query on the database. Is there a more efficient way to do this ?

The nodejs/express code :

exports.addTaskToList = function(req, res) {
    var listId = req.params.Id;
    var taskId = req.params.TaskId;
    Lists.update({_id: listId}, {$push: {items: taskId}}, {safe:true, upsert: true}, function(err, result){
        if(err) {
            console.log('Error updating todo list. ' + err);
        }
        else{
            console.log(result + ' todo list entry updated - New task added');
            Lists.findById(listId).populate('items').exec(function (err, updatedEntry) {
                if (err) {
                    console.log('Unable to retrieve todo list entry.');
                }
                res.send(JSON.stringify(updatedEntry));
            });
        }           
    });
};

Furthermore, the array items is an array of ObjectIds. Those items are in a separate schema so in a separate collection. Is it possible to push the whole object and not only its _id so that there is not another collection created ?

like image 277
GuillaumeA Avatar asked Dec 18 '13 20:12

GuillaumeA


People also ask

What is update return Mongoose?

By default, findOneAndUpdate() returns the document as it was before update was applied. You should set the new option to true to return the document after update was applied. Mongoose's findOneAndUpdate() is slightly different from the MongoDB Node.

What does .save return Mongoose?

The save() method is asynchronous, so it returns a promise that you can await on. When you create an instance of a Mongoose model using new, calling save() makes Mongoose insert a new document.

What is the difference between findOneAndUpdate and updateOne?

findOneAndUpdate returns a document whereas updateOne does not (it just returns the _id if it has created a new document).

What does findByIdAndUpdate return Mongoose?

Mongoose | findByIdAndUpdate() Function The findByIdAndUpdate() function is used to find a matching document, updates it according to the update arg, passing any options, and returns the found document (if any) to the callback.


2 Answers

use findOneAndUpdate() method and in query parameter use option as { "new": true}

return this.sessionModel
       .findOneAndUpdate({user_id: data.user_id}, {$set:{session_id: suuid}}, { "new": true})
       .exec()
       .then(data=>{
        return {
          sid: data.session_id
            }
        })
like image 166
KARTHIKEYAN.A Avatar answered Oct 17 '22 18:10

KARTHIKEYAN.A


The update method doesn't return the updated document:

However, if we don't need the document returned in our application and merely want to update a property in the database directly, Model#update is right for us.

If you need to update and return the document, please consider one of the following options:

Traditional approach:

Lists.findById(listId, function(err, list) {
    if (err) {
        ...
    } else {
        list.items.push(taskId)
        list.save(function(err, list) {
            ...
        });
    }
});

Shorter approach:

Lists.findByIdAndUpdate(listId, {$push: {items: taskId}}, function(err, list) {
    ...
});
like image 27
Mattias Farnemyhr Avatar answered Oct 17 '22 17:10

Mattias Farnemyhr