【问题标题】:Store mongoose query result in a variable将猫鼬查询结果存储在变量中
【发布时间】:2020-05-23 02:46:42
【问题描述】:

我有一个通过高阶函数返回的查询,如下所示:

查询:

const final_ids;

        final_ids = InterviewWorflowDao.findAll({}, (err, res) => {
            const user_ids = res.map(r => r.clientId);
            return user_ids;            
        })
console.log('show data', final_ids);

高阶函数

const findAll = (query, cb) => {
    model.find(query, null, cb);
}

我想要实现的是:将查询返回的id数组放入变量final_ids;console.log('show data', final_ids);总是返回我undefined

我也尝试了其他方法来达到同样的效果,但每次都给出 undefine。

请帮忙解决这个问题。

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:
    InterviewWorflowDao.findAll({}, function (err, docs) { 
       return new Promise( (res, rej) => {
    
         if (err) rej(err)
    
         res(docs)
      })
    });
    

    在你的高阶函数中

    const findAll = (query, cb) => {
    
        model.find(query, null, cb)
        .then( idDocs => console.log(idDocs))
        .catch(e => console.log(e));
    
    }
    

    其他选项:

    async function runQuery(){
      let modelIds = await findAll({},  (err, docs) => { 
              return docs
       });
    
       console.log(modelIds)
    
    }
    
    runQuery()
    

    霍夫:

    const findAll = (query, cb) => {
        return new Promise( (res, rej) => {
    
            res(model.find(query, '_id', cb))
    
        })
    }
    

    【讨论】:

    • 是的,HOF 中的模型是为数据库中的特定模式定义的模型
    • 在这个函数中, const findAll = (query, cb) => { model.find(query, null, cb); },我需要 findAll 的结果,以便它可以在其他地方使用。但即使结果在回调函数中可用,它也会给出未定义
    • 我改变我的答案,cheeckit
    • 我再次更改了答案,请看一下
    • 你能把它移到聊天室吗?
    【解决方案2】:

    查询函数是异步的,所以console.log函数和其他所有使用结果的东西都应该在回调中:

    InterviewWorflowDao.findAll({}, (err, res) => {
      const user_ids = res.map(r => r.clientId);
      console.log('show data', user_ids);
      return user_ids;            
    })
    

    【讨论】:

    • 我尝试了第一种方法。并且 Console.log('final ids', final_ids) 仍然未定义
    • 你能看看我的 HOF 吗?如果我可以在里面使用 async-await?
    • 异步等待方法,.findAll() 无法读取 const findAll。我还删除了 return 语句,但它不可读,因为 await IntervalWorkflowDao.findAll();
    猜你喜欢
    • 2017-05-08
    • 2014-07-25
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    • 2019-12-29
    • 2014-01-09
    • 1970-01-01
    • 2012-03-13
    相关资源
    最近更新 更多