通过多种方法返回猫鼬查询结果

时间:2020-03-06 00:27:33

标签: javascript node.js mongodb mongoose promise

我试图使用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。

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

1 个答案:

答案 0 :(得分:0)

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

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))
        });
    });
}