为什么 findbyidandupdate 没有将新评论推送到数组中



我正在尝试将数组中的注释添加到主注释中。在这里,我获取数据,使用它来创建新注释,然后将其推送到子数组中的父注释中。但是当它 findbyidandupdate 通过时,父注释在其子数组中没有此注释。我在它下面做了第二个发现,看看它是否返回新的更新的子数组,但没有返回任何内容。我正在将新评论的 id 输入到子数组中。

我的架构:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var PK = mongoose.Types.ObjectId;
var RK = mongoose.Schema.ObjectId;
var CommentSchema = Schema({
    body: {type: String},
    chapterId: {type: RK, ref: 'Chapter'},
    by: {type: RK, ref: 'User'},
    children: [{
        type: RK,
        ref: 'Comment'
     }]
}, {timestamps: true});
function autoPopulateComment() {
    this.populate('by');
}
CommentSchema.
pre('findOne', autoPopulateComment).
pre('find', autoPopulateComment);
module.exports = mongoose.model('Comment', CommentSchema)

;

我的控制器:

commentController.reply = function(req,res){
  var commentList;
  var newComment = new Comment(req.body);
  newComment.save();
  console.log(newComment);
  var commid = req.body.comid;
  //console.log(req.body.comid);
  //console.log(req.body.body);
  //console.log(req.body.xxchid);
  //console.log(req.body.by);

  Comment.findByIdAndUpdate(
    commid,
    {$push: {"children": newComment._id}},
    {new: true}

    )
  Comment.find({_id: commid}).then(function(comment){
    console.log(comment);
  })
  Chapter.find({_id: req.xxchid}).then(function(chapter){
    Comment.find({chapterId: req.xxchid}).then(function(data){

      return res.send({commentList: data, comidd: commid, test1:"testy"})
    })

  })
}

将更新功能更改为此功能,它起作用了。猜它需要一个回调耸耸肩。无论如何,THNX堆栈溢出!赫赫克斯德

Comment.findByIdAndUpdate(
    commid,
    {$push: {children: newComment}},
    {new: true}, 
     function(err, post){
      if(err){
        console.log(err);
      } else{
         console.log(post+"haha")

      }
     }

    )

最新更新