简体   繁体   English

如何在 findOne 方法中从 MongoDb 数据库返回 object

[英]How to return object from MongoDb database in findOne method

sorry if it's easy mistake, I've not so much experience in JS, I've tried a lot of ways and I can't resolve this problem.对不起,如果这很容易出错,我在 JS 方面没有太多经验,我尝试了很多方法,但我无法解决这个问题。

I can find and print my object from database, but I can't return it to my main method.我可以从数据库中找到并打印我的 object,但我无法将其返回到我的主要方法。

My main method (it's in another file than methods to database):我的主要方法(它在另一个文件中,而不是数据库方法):

(async () => {
    try{
        const someClass = new SomeClass();
        const object = await someClass.database.getFirstObjectFromBase("collectionName");
        console.log(object);
    } catch (err) {
        console.log(err);
    }
})();

and (before tries to debug this) my "object" is undefined.并且(在尝试调试之前)我的“对象”是未定义的。 Take a look on two methods I've used:看看我用过的两种方法:

async connectAndReturnWithFunction(func) {
    return new Promise(
        function(resolve, reject){
            mongoClient.connect(url, {}, (error, client) => {
                if (error) {
                    console.log("Cannot connect to db");
                } else {
                    console.log("Database connection established: " + dbname);
                };    
                const db = client.db(dbname);
                return func(db);
            }
        );
        }
    )
}

and last:最后:

async getFirstObjectFromBase(collection) {
    return await this.connectAndReturnWithFunction(function(db) {
        return db.collection(collection)
        .findOne({}, function(err, result) {
            console.log(result);
            return result;
        })
    })
}

I tried something with 'then' too:我也用“then”尝试了一些东西:

async getFirstObjectFromBase(collection) {
    return await this.connectAndReturnWithFunction(function(db) {
        return db.collection(collection)
        .findOne({})
        .then(result => {
            console.log(result); 
            return result;
        });
    })
}

In both examples of getFirstObjectFromBase console.log(result) print good object, but program just stop after this and I can't return this JSON to main method.在 getFirstObjectFromBase console.log(result) 的两个示例中,打印良好的 object,但程序在此之后停止,我无法将此 JSON 返回到主方法。

Thank you in advice:)谢谢你的建议:)

Problems in your code:您的代码中的问题:

  • Inside connectAndReturnWithFunction function, you never call resolve()connectAndReturnWithFunction function 内部,你永远不会调用resolve()

  • async functions always return a Promise , so you don't need to create one yourself using the Promise constructor. async函数始终返回Promise ,因此您无需使用Promise构造函数自己创建一个。 You never use await keyword inside connectAndReturnWithFunction function, so making it async is unnecessary.您永远不会在connectAndReturnWithFunction function 中使用await关键字,因此无需将其设为async

  • Inside connectAndReturnWithFunction function, inside the the callback function of mongoClient.connect , in case of an error, you log a message indicating that connection to database couldn't be established but the last two lines of codeconnectAndReturnWithFunction function 内部,在 mongoClient.connect 的回调mongoClient.connect内部,如果出现错误,您会记录一条消息,指示无法建立与数据库的连接,但最后两行代码

    const db = client.db(dbname); return func(db);

    will still execute.仍将执行。 You probably meant to add those two lines inside the else block.您可能打算在else块中添加这两行。

     mongoClient.connect(url, {}, (error, client) => { if (error) { console.log("Cannot connect to db"); } else { console.log("Database connection established: " + dbname); const db = client.db(dbname); return func(db); } }

Reasone why object is undefined because inside the connectAndReturnWithFunction , you never call resolve() , which is needed to resolve the Promise with the data from the database.未定义object的原因是因为在connectAndReturnWithFunction内部,您永远不会调用resolve() ,这是使用数据库中的数据解析Promise所必需的。

To fix the problem, pass the resolve() and reject() functions to the callback function of connectAndReturnWithFunction function.要解决此问题,请将resolve()reject()函数传递给connectAndReturnWithFunction function 的回调 function。

return func(db);

to

func(db, resolve, reject);

and inside the getFirstObjectFromBase function, call the resolve() function, passing in the result as an argument.getFirstObjectFromBase function 中,调用resolve() function,将result作为参数传递。 In case of an error, call the reject() function, passing in the error object as an argument.如果出现错误,调用reject() function,将错误 object 作为参数传入。

async getFirstObjectFromBase(collection) {
   return this.connectAndReturnWithFunction(function(db, resolve, reject) {
       return db.collection(collection)
         .findOne({}, function(err, result) {
             if (err) {
                reject(err);
             } else {
                resolve(result);
             }
         })
   })
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM