Return updated collection with Mongoose

Viewed 38726

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 ?

3 Answers
Related