我一直在尝试返回一个数组(childz),它接受链式promises中循环mongoose查询的结果但是当我在consolelog结果时它仍然是一个空数组。我之前确实嵌套过,但我认为链接它要好得多,但我仍然不知道如何正确地返回这些异步结果。
SCHEMA:
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});
CODE:
commentController.reply = function(req,res){
var commentList;
var newComment = new Comment(req.body);
newComment.save();
//console.log(newComment);
var commid = req.body.comid;
var dataa;
//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}},
{new: true},
function(err, post){
if(err){
console.log(err);
} else{
//console.log(post+"haha")
}
}
)
var childz = [];
Comment.find({chapterId: req.body.xxchid}).then(function(data){
//console.log(data+"data");
dataa = data;
//console.log(dataa+"dataa");
}).then(function(){
Comment.find({_id: commid}).then(function(onlydata){
for(var i=0;i<onlydata[0].children.length;i++){
Comment.find({_id: onlydata[0].children[i]}).then(function(onlydatac){
childz.push(onlydatac[0].body);
console.log(childz+"imchildz");//does print this as it should. shows all the elements appropriate
})
}
})
}).then(function(result){
console.log(result+"result");
for(var i=0;i<childz.length;i++){ //doesnt print out anything.
console.log(childz[i]+"really"+i);
}
console.log(childz); //shows an empty array []
return res.send({commentList: dataa, comidd: commid, childs: childz})
})
}
答案 0 :(得分:0)
有两个错误。首先使用accumulate
正在使用回调接口,然后你也在调用它。其次,你没有在“父母”承诺中回报承诺。
Comment.findByIdAndUpdate
您还可以使用Comment.findByIdAndUpdate(commid, {$push: {children: newComment}}, {new: true})
.exec()
.then(post => {
var childz = [];
return Comment.find({chapterId: req.body.xxchid})
.exec()
.then(function(data){
var dataa = data; // don't know the use of it
return Comment.find({_id: commid})
.exec()
.then(onlydata => {
return Promise.all(onlydata[0].children.map(child => {
return Comment.find({_id: child})
.exec()
.then((onlydatac) => {
childz.push(onlydatac[0].body);
});
}));
});
.then(() => {
return childz;
});
});
});
使事情更容易理解。
async-await