无法使用node.js和mongodb以同步方式调用函数

无法使用node.js和mongodb以同步方式调用函数,node.js,mongodb,synchronous,Node.js,Mongodb,Synchronous,我试图使用node.js同步调用中的某个函数,但根据我的代码,它没有发生。我在下面解释我的代码 viewDraggedFileContent = async(req, res) => { try{ let id = req.params.id; if(!id) { responseObj = { status: 'error', msg: 'Please sen

我试图使用node.js同步调用
中的某个函数,但根据我的代码,它没有发生。我在下面解释我的代码

viewDraggedFileContent = async(req, res) => {

    try{
        let id = req.params.id;
        if(!id) {
            responseObj = {
                status: 'error',
                msg: 'Please send the mongo id to fetch the file content.',
                body: {}
            };
            res.send(responseObj);
        }else{
            let response = await findOne(id, 'useCaseFile');
            console.log('res', response);
            if(response['status'] === 0) {
                responseObj = {
                    status: 'error',
                    msg: `Error occurred`,
                    body: response['data']
                };
                res.send(responseObj);
            }else{
                const resObj = [{
                    fileData: response.data.fileData,
                    _id: response['data']['_id']
                }]
                responseObj = {
                    status: 'success',
                    msg: `Fetched data successfully`,
                    body: resObj
                };
                res.send(responseObj);
            }
        }
    }catch(error) {
        console.log('Error::', error);
    }
}

/**
 * 1- Method to fetch single record from mongoDB as per _id.
 */

findOne = async (id, collName) => {
    try{
        let mongoID = new ObjectId(id);
        MongoClient.connect(dbUrl, dbOptions).then(function (client) {
            let connObj = client.db(dbName);
            connObj.collection(collName).findOne({ _id: mongoID }, function (error, doc) {
                if (error) {
                    client.close();
                    return {
                        status: 0,
                        data: error
                    };
                } else {
                    client.close();
                    return {
                        status: 1,
                        data: doc
                    };
                }
            })
        })
    }catch(error){
        console.log('Error while fetching single record::', error);
    }
}

这里我从
viewdraggedfelecontent
函数调用
findOne
函数。我的目标是,一旦所需数据从
findOne
函数返回,然后
console.log('res',response')应该执行,但按照我的代码
console.log('res',response)在从
findOne
获取响应之前执行。我还使用了
async--wait
,但它仍然异步运行
。这里我需要在收到
findOne
函数的响应后显示控制台消息。

我认为您的问题在于您没有返回承诺,因此调用findOne函数的线路没有等待任何东西

这里有两种解决方案:

当您将回调传递给db.collection.findOne函数时,它不会返回任何内容,但如果不返回,则可以等待结果,如下所示:

const doc = await connObj.collection(collName).findOne({ _id: mongoID })
findOne = async (id, collName) => {
  return new Promise((resolve, reject) => {
    try{
      let mongoID = new ObjectId(id);
      MongoClient.connect(dbUrl, dbOptions).then(function (client) {
        let connObj = client.db(dbName);
        connObj.collection(collName).findOne({ _id: mongoID }, function (error, doc) {
          if (error) {
            client.close();
            reject(error);
          } else {
            client.close();
            resolve(doc);
          }
        })
      })
    }catch(error){
      console.log('Error while fetching single record::', error);
    }
  }
}
然后,您可以解析您的文档并返回它

另一种解决方案是,在findOne函数中返回一个承诺,然后使用resolve发送结果,如下所示:

const doc = await connObj.collection(collName).findOne({ _id: mongoID })
findOne = async (id, collName) => {
  return new Promise((resolve, reject) => {
    try{
      let mongoID = new ObjectId(id);
      MongoClient.connect(dbUrl, dbOptions).then(function (client) {
        let connObj = client.db(dbName);
        connObj.collection(collName).findOne({ _id: mongoID }, function (error, doc) {
          if (error) {
            client.close();
            reject(error);
          } else {
            client.close();
            resolve(doc);
          }
        })
      })
    }catch(error){
      console.log('Error while fetching single record::', error);
    }
  }
}

然后,您不再需要状态,可以使用Then和catch来获得结果。

我认为您的问题在于您没有返回承诺,因此调用findOne函数的线路不会等待任何结果

这里有两种解决方案:

当您将回调传递给db.collection.findOne函数时,它不会返回任何内容,但如果不返回,则可以等待结果,如下所示:

const doc = await connObj.collection(collName).findOne({ _id: mongoID })
findOne = async (id, collName) => {
  return new Promise((resolve, reject) => {
    try{
      let mongoID = new ObjectId(id);
      MongoClient.connect(dbUrl, dbOptions).then(function (client) {
        let connObj = client.db(dbName);
        connObj.collection(collName).findOne({ _id: mongoID }, function (error, doc) {
          if (error) {
            client.close();
            reject(error);
          } else {
            client.close();
            resolve(doc);
          }
        })
      })
    }catch(error){
      console.log('Error while fetching single record::', error);
    }
  }
}
然后,您可以解析您的文档并返回它

另一种解决方案是,在findOne函数中返回一个承诺,然后使用resolve发送结果,如下所示:

const doc = await connObj.collection(collName).findOne({ _id: mongoID })
findOne = async (id, collName) => {
  return new Promise((resolve, reject) => {
    try{
      let mongoID = new ObjectId(id);
      MongoClient.connect(dbUrl, dbOptions).then(function (client) {
        let connObj = client.db(dbName);
        connObj.collection(collName).findOne({ _id: mongoID }, function (error, doc) {
          if (error) {
            client.close();
            reject(error);
          } else {
            client.close();
            resolve(doc);
          }
        })
      })
    }catch(error){
      console.log('Error while fetching single record::', error);
    }
  }
}

然后,您不再需要状态,可以使用Then和catch获得结果。

您可以在findOne函数中使用
async/await

异步函数findOne(id,collName){ const client=wait MongoClient.connect(url{ useUnifiedTopology:正确, }).catch((错误)=>{ log(“连接到数据库时出错”,err); }); 如果(客户){ 试一试{ 设mongoID=newobjectid(id); 让connObj=client.db(dbName); 让doc=wait connObj.collection(collName.findOne)({u id:mongoID}); 返回{ 现状:1, 资料:doc,, }; }捕获(错误){ log(“获取单个记录时出错::”,错误); 返回{ 状态:0, 数据:错误, }; }最后{ client.close(); } } }
您可以在findOne函数中使用
async/await

异步函数findOne(id,collName){ const client=wait MongoClient.connect(url{ useUnifiedTopology:正确, }).catch((错误)=>{ log(“连接到数据库时出错”,err); }); 如果(客户){ 试一试{ 设mongoID=newobjectid(id); 让connObj=client.db(dbName); 让doc=wait connObj.collection(collName.findOne)({u id:mongoID}); 返回{ 现状:1, 资料:doc,, }; }捕获(错误){ log(“获取单个记录时出错::”,错误); 返回{ 状态:0, 数据:错误, }; }最后{ client.close(); } } }
它抛出了这个
错误::ReferenceError:client未定义
错误。很抱歉。我已经更新了答案,请检查它是否抛出此
错误::ReferenceError:客户端未定义
错误。对此表示抱歉。我已经更新了答案,请检查