由于异步调用,猫鼬检索到的数据为空

时间:2018-10-19 15:14:43

标签: node.js mongodb mongoose

由于mongoDB的异步性质,我在假设时遇到问题。 假设我有这样的架构:

const TopicSchema = new mongoose.Schema({
    name: {type:String,unique:true},
    sub_topic:[{type:mongoose.Schema.Types.ObjectId, ref : 'Topic'}] 
});
我想做一个函数来返回一个带有sub_topic中的id的数组。 我尝试了这个但没有成功:

let subs;
subs = getSubs(req.params.id)
console.log('returned subs', subs)

function getSubs (dadID) {
    let subs = [];
    Topic.findById(dadID,function(err,res){
      console.log('res : ',res);
      subs=subs.concat(res.sub_topic);
      console.log('subs after concat:',subs)
    })
    console.log('subs after Topic.find:',subs)
    return subs;
  }

如您在结果中看到的。 concat之后的潜艇是正确的。但是

  

返回子的调用发生在查询返回之前,并启动了我给它的回调函数

结果是:

subs after Topic.find: []
returned subs []
res :  { sub_topic:
   [ 5bc9c894740a2a52f906a95c,
     5bc9c894740a2a52f906a95f,
     5bc9c894740a2a52f906a960 ],
  _id: 5bc9c894740a2a52f906a95b,
  name: 'A',
  __v: 0 }
subs after concat: [ 5bc9c894740a2a52f906a95c,
  5bc9c894740a2a52f906a95f,
  5bc9c894740a2a52f906a960 ]

如果我只想返回完整文档作为退货,该怎么办。 能做到吗?

1 个答案:

答案 0 :(得分:0)

设为async

let subs;
subs = getSubs(req.params.id)
  .then((subs) => {
    // do something with subs or the topic
  });

async function getSubs (dadID) {
    let subs = [];
    const topic = await Topic.findById(dadID);
    subs=subs.concat(topic.sub_topic);
    return subs; // or return the topic
}