Node.js 将mongoose查询结果存储在变量中

Node.js 将mongoose查询结果存储在变量中,node.js,mongoose,Node.js,Mongoose,我有一个通过高阶函数返回的查询,如下所示: 查询: const final_ids; final_ids = InterviewWorflowDao.findAll({}, (err, res) => { const user_ids = res.map(r => r.clientId); return user_ids; }) console.log('show data',

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

查询:

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);
}
const findAll = (query, cb) => {

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

}
我想要实现的是:将查询返回的id数组放入变量
final\u id中
console.log('show data',final_id)总是返回我
未定义的

我也尝试过其他方法来达到同样的效果,但每次都会产生不确定性


请帮助解决此问题。

查询函数是异步的,因此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函数和使用结果的所有其他函数都应该在回调中:

InterviewWorflowDao.findAll({}, (err, res) => {
  const user_ids = res.map(r => r.clientId);
  console.log('show data', user_ids);
  return user_ids;            
})
在你的高阶函数中

const findAll = (query, cb) => {
    model.find(query, null, cb);
}
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) => {
    model.find(query, null, cb);
}
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()
霍夫:


我尝试了第一种方法。和Console.log('final id',final_id)仍然未定义您可以查看我的HOF吗?如果我可以在其中使用async await?async await方法,const findAll不能被.findAll()读取。我还删除了return语句,但它不可读,因为wait IntervalWorkflowDao.findAll();我尝试了第一种方法。和Console.log('final id',final_id)仍然未定义您可以查看我的HOF吗?如果我可以在其中使用async await?async await方法,const findAll不能被.findAll()读取。我还删除了return语句,但它不可读,因为wait IntervalWorkflowDao.findAll();是的,HOF中的模型是为数据库中的特定模式定义的模型在这个函数中,const findAll=(query,cb)=>{model.find(query,null,cb);},我需要findAll中的结果,以便它可以在其他地方使用。但是它给出了未定义的结果,即使结果在回调函数中可用我更改了我的答案,cheeckitI再次更改了我的答案jaja cheeck请您将其移动到聊天室?是的,HOF中的模型是为数据库中的特定模式定义的模型在该函数中,const findAll=(query,cb)=>{model.find(query,null,cb);},我需要findAll中的结果,这样它就可以在其他地方使用。但是它给出了未定义的结果,即使在回调函数中的结果可用。我更改了我的答案,cheeckitI再次更改了我的答案jaja cheeck请您将其移动到聊天室好吗?