【问题标题】:Loop of findOne in mongoose issue猫鼬问题中的 findOne 循环
【发布时间】:2021-08-19 20:34:20
【问题描述】:

我在使用 mongoose findOne 循环时遇到问题。

我有一个 ObjectID 数组,我需要获取文档的另一个值(value 关键字) 这是我目前所拥有的:

 
let qarray = []
  

   for (var i = 0; i < req.body.keyword.length; i++) {
     let pushy = db.collection('keywords').findOne({ "_id": req.body.keyword[i]})
    qarray.push(pushy.keyword)
    console.log(pushy); // for debugging purpose
    console.log(req.body.keyword[i]); // for debugging purpose
   }
   console.log(qarray);

那个结果:

Promise { <pending> }
60ab81c5be36d74968e23d14
Promise { <pending> }
60a77893b015d85f38a3323f
[ undefined, undefined ]

编辑

我选择了循环解决方案,但我对异步函数不是很熟悉......

async function fetchSomeStuff(expTemp){
let qarray = []
for (var i = 0; i < expTemp.keywordid.length; i++) {
  console.log(expTemp.keywordid);
  console.log(db.collection('keywords').findOne({ _id: expTemp.keywordid[i]}));
  let pushy = await db.collection('keywords').findOne({ _id: expTemp.keywordid[i]})
  .catch(error => console.error(error))
  .then(qarray.push(pushy.keyword))
}
console.log(qarray);
}

这给了我这些问题消息:

承诺'{待处理}'

ReferenceError: 在初始化之前无法访问 'pushy'

我想我必须等待数据库获取然后放入我的数组中,我肯定错过了一些东西

【问题讨论】:

    标签: javascript node.js mongodb loops mongoose


    【解决方案1】:

    改用 $in

    async function fetchSomeStuff(){
      const pushy = await db.collection('keywords').find({"_id" : { $in : req.body.keyword}});
      return pushy;
    }
    

    或者如果你仍然想循环使用 findOne()

    async function fetchSomeStuff(){
      let qarray = []
      
    
      for (var i = 0; i < req.body.keyword.length; i++) {
        let pushy = await db.collection('keywords').findOne({ "_id": req.body.keyword[i]})
        qarray.push(pushy.keyword)
        console.log(pushy); // for debugging purpose
        console.log(req.body.keyword[i]); // for debugging purpose
      }
    
      console.log(qarray);
    }
    

    【讨论】:

    • 我选择了循环解决方案,并且我已经更新了答案。我对异步函数很陌生,还有很多东西要学。为什么 ReferenceError: Cannot access 'pushy' before initialization 意味着? .then 不会让它等待答案吗?
    • @VortexSensei 你在等待时不需要 .then()catch(),而是将它们包装到 try catch 中
    • try catch 解决了我的问题,非常感谢!
    猜你喜欢
    • 2012-11-07
    • 2014-08-12
    • 1970-01-01
    • 2018-01-10
    • 2011-10-25
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多