存储MongoDB结果(承诺待定)

时间:2018-07-28 11:15:10

标签: javascript node.js mongodb

我一直试图将MongoDB字段值存储为变量,但是得到了Promise {< pending >}。我一直以为我知道如何发出异步请求,但似乎我真的不知道。

exports.main = (req, res, next) => {

    const dt = Post.findOne({ active: true }, function(err, data) {

        if (err) throw err;

        return data;

    }).sort({ $natural: -1 }).exec().then(doc => {

        return(doc);

    });

    // Logs --> Promise { <pending> }
    console.log(dt); 

}

3 个答案:

答案 0 :(得分:1)

如果要访问查询结果,则应在查询的callback.then中进行操作:

exports.main = (req, res, next) => {

    let promise = Post.findOne({ active: true }).sort({ $natural: -1 }).exec();

    promise.then((doc) => {
         console.log(doc);
         res.send(doc); // send data if needed. I think this is express route handler
    })
    .catch((err) => {
       console.log(err);
       next();
    })
}

答案 1 :(得分:1)

这是一个类似于this popular one的问题。

所有依赖查询结果的操作都应在then内部执行:

Post.findOne({ active: true }).sort({ $natural: -1 }).exec().then(dt => {
    ...
});

findOne回调参数对于Promise来说不是必需的。

async..await通常可用于类似同步的控制流:

exports.main = async (req, res, next) => {
    try {
        const dt = await Post.findOne({ active: true }).sort({ $natural: -1 }).exec();
        ...
        next(); // if necessary
    } catch (error) {
        next(error);
    }
}

this answer中所述,由于Express无法处理承诺,开发人员应通过将整个async函数体包装为try..catch来处理所有错误。

答案 2 :(得分:1)

猫鼬exec()方法为您提供了完整的承诺,并且当您在then中返回值时

    <div id="Signupin" class="col-xs-12 col-sm-6 col-md-4 container-fluid" style = "height: 70px; margin: 0px; padding: 0px;">
                       <div class="row" style=" height: 70px;">
                        <div id = "Sign" class = "col-xs-4 col-sm-4 col-md-4" style = "font-size:50px;   text-align: center; height: 65px;  background-color: white;">
                           <p style = "margin: 0px; padding:  0px;font-family: monospace;">Sign</p> 
                        </div>
                        
                         <!-- I would like to change background color of these two(Up and In) when the mouse is overlayed. -->
                         
                         <a href="C:\FreeGuide\HTML_CSS\Sign Up\signup.html">
                          
                         <div id = "Up" class = "col-xs-4 col-sm-4 col-md-4" style="height: 70px; text-align: center; background-color: #B7B7AC ">    
                         
                         <p style = "font-size: 50px; color: gainsboro;font-family: monospace;">Up</p>
                        </div>                      
                          </a>
                          
                        <a>
                        <div id = "In" class = "col-xs-4 col-sm-4 col-md-4" style = "background-color: #0E2E2F;text-align: center; height: 70px; 
                        ">
                        
                        <p  style = "font-size: 50px;font-family: monospace; color: gainsboro;">In</p>
                        
                        </div>
                           </a>
                    </div>
                    </div>
                          

这将返回一个处于待处理状态的Promise,就像您当前所得到的一样。

有多种方法可以退回文档。使用异步/等待,请遵循以下模式:

...exec().then(doc => {

    return(doc); // <-- returns a pending promise

});

使用回调函数

exports.main = async (req, res, next) => {  
    try {
        const data = await Post.findOne({ active: true }).sort({ $natural: -1 }).exec();
        console.log(data);

        res.status(200).send(data);
    } catch(err) {
        console.error(err);
        next();
    }
}

使用诺言

exports.main = (req, res, next) => {
    Post.findOne({ active: true }).sort({ $natural: -1 }).exec((err, data) => {
        if (err) throw err;
        console.log(data);

        res.status(200).send(data);
    });
}