递归的猫鼬模型没有正确存储我的数据

时间:2016-02-20 20:25:39

标签: node.js mongoose

在研究节点时,我正在尝试创建一个小注释应用程序。由于我使用的书有点过时,我不得不调整书中提供的模型以使应用程序运行。但是,我认为我的模型仍然存在问题,因为部分数据存储为对象Object。有没有人在模型中看到问题?

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;
var ReplySchema = new Schema();
ReplySchema.add({
  username: String,
  subject: String,
  timestamp: { type: Date, default: Date.now },
  body: String,
  replies:[ReplySchema]
}, { _id: true });

var CommentThreadSchema = new Schema({
    title: String,
    replies:[ReplySchema]
});
mongoose.model('Reply', ReplySchema);
mongoose.model('CommentThread', CommentThreadSchema);

Mongo的结果:

{ _id: 56c8c91b011c7db2608159d6,   
  '[object Object]timestamp': Sat Feb 20 2016 21:14:19 GMT+0100 (CET),   '[object Object]replies': [] }

控制器

var mongoose = require('mongoose'),
    CommentThread = mongoose.model('CommentThread'),
    Reply = mongoose.model('Reply');
exports.getComment = function(req, res) {
  CommentThread.findOne({ _id: req.query.commentId })
  .exec(function(err, comment) {
    if (!comment){
      res.json(404, {msg: 'CommentThread Not Found.'});
    } else {
      res.json(comment);
    }
  });
};
exports.addComment = function(req, res) {
  CommentThread.findOne({ _id: req.body.rootCommentId })
  .exec(function(err, commentThread) {
    if (!commentThread){
      res.json(404, {msg: 'CommentThread Not Found.'});
    } else {
      var newComment = Reply(req.body.newComment);
      newComment.username = generateRandomUsername();
      addComment(req, res, commentThread, commentThread, 
                 req.body.parentCommentId, newComment);
    }
  });
};
function addComment(req, res, commentThread, currentComment, 
                    parentId, newComment){
  if (commentThread.id == parentId){
    console.log(newComment);
    commentThread.replies.push(newComment);
    updateCommentThread(req, res, commentThread);
  } else {
    for(var i=0; i< currentComment.replies.length; i++){
      var c = currentComment.replies[i];
      if (c._id == parentId){
        c.replies.push(newComment);
        var replyThread = commentThread.replies.toObject();
        updateCommentThread(req, res, commentThread);
        break;
      } else {
        addComment(req, res, commentThread, c, 
                   parentId, newComment);
      }
    }
  }
};
function updateCommentThread(req, res, commentThread){
  CommentThread.update({ _id: commentThread.id }, 
      {$set:{replies:commentThread.replies}})
  .exec(function(err, savedComment){
    if (err){
     res.json(404, {msg: 'Failed to update CommentThread.'});
    } else {
     res.json({msg: "success"});
    }
  });
}
function generateRandomUsername(){
  //typically the username would come from an authenticated session
  var users=['Mojos', 'Milo', 'Mihaal', 'Haly', 'MilodeBaesz', 'Mihaly'];
  return users[Math.floor((Math.random()*5))];

}

0 个答案:

没有答案