【问题标题】:Return Mongoose query result through multiple methods通过多种方法返回 Mongoose 查询结果
【发布时间】:2020-06-18 16:56:51
【问题描述】:

我正在尝试使用 Mongoose 从 MongoDB 数据库中检索数据以访问数据,但是我正在尝试通过几种方法检索数据。这是我的retrieveDocument 方法:

function retrieveDocument(collectionName, schema, _id) {
    conn.once('open', async () => {
        var model = mongoose.model(collectionName, schema, collectionName)
        return await model.findById(_id)
    });
}

以及我如何调用该方法:

function retrieveUserDocument(_id){
    return retrieveDocument("User", some_Schema, _id);
}
console.log(retrieveUserDocument("some_Id"));

但是结果并没有被打印出来,而是代码正在记录undefined,因为model.findById(_id) 方法返回了一个Promise。

如何打印出上面定义的结构中的结果?

【问题讨论】:

    标签: javascript node.js mongodb mongoose promise


    【解决方案1】:

    我认为你应该在这里尝试一下 promise。它可能会起作用,您应该在调用猫鼬模型时尝试等待。试试下面写的代码

    function retrieveDocument(collectionName, schema, _id) {
        return new Promise(async(resolve, reject) => {
            conn.once('open', async () => {
                var model = await mongoose.model(collectionName, schema, collectionName)
                resolve(model.findById(_id))
            });
        });
    }
    

    【讨论】:

    • 非常感谢您的回复,我将连接包装在一个承诺中,它成功了!只是一两个更改:(resolve,reject) 之前的async 是不必要的,model 调用之前的await 没有任何效果。相反,我需要在model.findById() 调用之前保留它。无论如何,将连接调用包装在Promise 中并在find 调用上调用resolve 是有效的!
    猜你喜欢
    • 2020-11-25
    • 1970-01-01
    • 2021-07-22
    • 2015-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多