node.js - Why can't I update this MongodDB document in the first callback function (while I'm able to update a different document without issues)? -
sorry if title confusing, had hard time summarizing problem in single question. implementing comment system generic article posting/reading web app using mean stack.
i have models author
, article
, , comment
following (omitting irrelevant fields createdby):
var authorschema = new schema({ // removing unnecessary fields articles: [{ type: schema.objectid, ref: 'article' }], comments: [{ // want find of users comments type: schema.objectid, ref: 'comment' }] ... } var commentschema = new schema({ // removing unnecessary fields content: { type: string }, author: { // want able find comment's author type: schema.objectid, ref: 'author' }, ... } var articleschema = new schema({ content: { type: string }, author: { type: schema.objectid, ref: 'author' }, comments: [{ type: schema.objectid, ref: 'comment' }] ... }
here code creating comment in comment controller:
commentctrl.createcomment = function(req, res, next) { var comment = new comment(req.body); if (req.user) { comment.author = req.user; // desired article stored on req object earlier middleware req.article.comments.unshift(comment); // naive way add comment req.article.save( function(err) { if (err) { return senderror(res, 400, geterrormessage(err)); } else { author.findbyidandupdate( req.user._id, {$push: {comments: comment}}, function(err){ res.json(comment); } ) } }); } else { return senderror(res, 401,'the user not logged in.'); } };
so weird part. author correctly storing comment in comments array field whereas article not. after execution, here console log of article references author (again, removed irrelevant fields clarity):
{ _id: 56a7b5028bffef9e1ba58ab4, author: { _id: 56a7b1791a5f728c1bb1ee99, username: 'xtest1', comments: [ 53a78291a5f728c1bbcef9b ], articles: [ 53a78291a5f728c1bbcef9a ], }, title: 'test article', content: '...', comments: [] }
my original thought naive approach of unshifting comment comments array not working, while had article object on req object, changed implementation mimic code seems working updating author:
article.findbyidandupdate( req.article._id, {$push: {comments: comment}}, function(err){ ... // same inner function above (to update author) } }
that didn't change @ all. i'm not getting error messages (which makes sense since inner callback working fine), have no idea what's going on.
i figured out problem, , feel bit silly. answering own question, can prevent others same mistake.
i not creating comment document in database. creating comment in application, storing references (or rather, trying to) in author , article documents.
the solution first save comment in db, carry out original code in successful callback function.
the 1 thing can't figure out why storing reference in author object @ all? if has ideas might shed light on dormant problem can't foresee.
Comments
Post a Comment