【问题标题】:How to retrieve the mongodb query result from a promise?如何从 Promise 中检索 mongodb 查询结果?
【发布时间】:2018-02-18 21:43:31
【问题描述】:

我正在尝试在“/read/:id”路由中检索 db.collection 查询的结果。当找到一个用户时,promise 被履行并发送状态“成功”。然而,数据对象是空的。

查询:

const getDb = require('./connection').getDb,
    ObjectId = require('mongodb').ObjectId;

readUser: async function(data) {
    let o_id = new ObjectId(data);
    await getDb().collection('users').find({ _id: o_id })
    }

路线:

const express = require('express'),
router = express.Router(),
queries = require('../db/queries');

router.get('/read/:id', (req, res) => {
queries.readUser(req.params.id)
    .then((user) => {
        res.status(200).json({
            status: 'success',
            data: user
        })
    })
    .catch((err) => {
        res.status(500).json({
            status: 'error',
            data: err
        });
    });
})

res.json

{
    "status" : "success"
}

谁能解释如何成功检索查询的数据?

请找到项目代码here

谢谢。

【问题讨论】:

  • 为什么不从 readUser 函数返回任何内容?
  • 你会回到哪里?在回调中?
  • 你正在使用await,所以不需要传递回调函数,只需在await之前添加return,它就会返回你想要的数据。
  • 返回等待的结果是:{ "status" : "error", "data" : {} }
  • 你能不能尝试传递回调和控制台。记录你在回调函数中得到的数据。

标签: javascript node.js mongodb


【解决方案1】:

好的,我找到了解决方案。

readUser: async function(data) {
            let o_id = new ObjectId(data),
                cursor = getDb().collection('users').find({ _id: o_id });
            return await cursor.next() // returns document result of collection.find() method
        }

【讨论】:

    猜你喜欢
    • 2017-07-22
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    相关资源
    最近更新 更多