Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
88
rated 0 times [  89] [ 1]  / answers: 1 / hits: 39125  / 11 Years ago, wed, december 18, 2013, 12:00:00

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 ?


More From » node.js

 Answers
18

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) {
...
});

[#73669] Tuesday, December 17, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trinityr

Total Points: 49
Total Questions: 107
Total Answers: 96

Location: Mayotte
Member since Fri, Oct 1, 2021
3 Years ago
;