简体   繁体   中英

How to retrieve the mongodb query result from a promise?

I am trying to retrieve the result of a db.collection query in the "/read/:id" route. When a user is found,the promise is fulfilled and status 'success' is sent. The data object is, however, empty.

Query:

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

Route:

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"
}

Could anybody explain how to successfully retrieve the data of the query?

Please find the project code here .

Thank you.

Alright, I found a solution.

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
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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