我正在尝试将数组中的注释添加到主评论中。在这里,我将获取数据,使用它来创建新注释,然后将其推送到子数组中的父注释中。但是当findbyidandupdate通过时,父注释在其子数组中没有这个注释。 我在它下面做了第二次查找,看它是否返回新更新的子数组,但没有。我正在将新注释的id输入到children数组中。
我的架构:
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"})
})
})
}
答案 0 :(得分:1)
将更新功能更改为此功能并且有效。猜猜它需要一个回调耸肩。无论如何thnx stackoverflow! hehexd
Comment.findByIdAndUpdate(
commid,
{$push: {children: newComment}},
{new: true},
function(err, post){
if(err){
console.log(err);
} else{
console.log(post+"haha")
}
}
)