Mongoose: MongoDB followers and following structure on update
Problem
I'm doing a following and followers addons to my code: here is the code.
In summary, the workflow is like this: I update an array of followers adding the ObjectId of the following person and vice versa, however at the first update, my doc returns 0, it means that is hasnt been update, do you have any hint?
if (typeof(req.body.userToFollow) != 'undefined') {
var conditions = { _id: req.user._id }
, update = {"$addToSet":{following: req.body.userToFollow}}
, options = {};
Users.update(conditions, update, options, function(err, doc){
if (!err && doc) {
var reconditions = { _id: req.body.userToFollow }
, reupdate = {"$addToSet": { followers : req.user._id } }
, reoptions = {};
Users.update(conditions, update, options, function(err, doc){
if (!err && doc) {
var body = JSON.stringify(doc);
res.header('Content-Type', 'application/json');
res.end(body);
} else {
console.log(err);
}
});
} else {
console.log("\n\n\n\n\n");
console.log(doc);
}
});
}
many thanks
Problem courtesy of: nick
Solution
Use safe mode by passing {safe:true}
in the options to update(). Then you will be able to check the status of the update.
Solution courtesy of: mpobrien
Discussion
View additional discussion.