118

I have tried to use Mongoose to send the list of all users as follows:

server.get('/usersList', function(req, res) {
    var users = {};

    User.find({}, function (err, user) {
        users[user._id] = user;
    });

    res.send(users);
});

Of course, res.send(users); is going to send {}, which is not what I want. Is there a find alternative with slightly different semantics, where I could do the following?

server.get('/usersList', function(req, res) {    
    User.find({}, function (err, users) {
        res.send(users);
    });
});

Essentially, I want the callback to be executed only when all the users have been fetched from the database.

4

10 に答える 10

191

_idまあ、本当にからへのマッピングを返したい場合はuser、いつでも次のことができます。

server.get('/usersList', function(req, res) {
  User.find({}, function(err, users) {
    var userMap = {};

    users.forEach(function(user) {
      userMap[user._id] = user;
    });

    res.send(userMap);  
  });
});

find()配列内の一致するすべてのドキュメントを返すため、最後に切り取られたコードがその配列をクライアントに送信します。

于 2012-12-31T16:07:44.007 に答える
16

If you'd like to send the data to a view pass the following in.

    server.get('/usersList', function(req, res) {
        User.find({}, function(err, users) {
           res.render('/usersList', {users: users});
        });
    });

Inside your view you can loop through the data using the variable users

于 2016-02-05T18:00:02.587 に答える
10

There was the very easy way to list your data :

server.get('/userlist' , function (req , res) {
 User.find({}).then(function (users) {
 res.send(users);
 });
});
于 2018-05-24T06:45:17.650 に答える
9

This is just an Improvement of @soulcheck 's answer, and fix of the typo in forEach (missing closing bracket);

    server.get('/usersList', (req, res) => 
        User.find({}, (err, users) => 
            res.send(users.reduce((userMap, item) => {
                userMap[item.id] = item
                return userMap
            }, {}));
        );
    );

cheers!

于 2014-06-10T09:30:54.947 に答える
4

Same can be done with async await and arrow function

server.get('/usersList', async (req, res) => {

const users = await User.find({});

const userMap = {};
users.forEach((user) => {
    userMap[user._id] = user;
});

res.send(userMap);

});
于 2019-08-25T07:46:03.163 に答える
1

In case we want to list all documents in Mongoose collection after update or delete

We can edit the function to some thing like this:

exports.product_update = function (req, res, next) {
        Product.findByIdAndUpdate(req.params.id, {$set: req.body}, function (err, product) {
            if (err) return next(err);
            Product.find({}).then(function (products) {
                res.send(products);
                });
            //res.send('Product udpated.');
        });
    };

This will list all documents on success instead of just showing success message

于 2019-01-05T01:27:47.677 に答える
1

To make function to wait for list to be fetched.

getArrayOfData() {
    return DataModel.find({}).then(function (storedDataArray) {
        return storedDataArray;
    }).catch(function(err){
        if (err) {
            throw new Error(err.message);
        }
    });
}
于 2019-10-29T18:26:46.840 に答える
0

My Solution

User.find()
        .exec()
        .then(users => {
            const response = {
                count: users.length,
                users: users.map(user => {

                    return {
                        _id: user._id,
                        // other property
                    }

                })

            };
            res.status(200).json(response);
        }).catch(err => {
        console.log(err);
        res.status(500).json({
            success: false
        })
    })
于 2020-01-07T19:10:06.690 に答える
0

You can try this -

User.find().exec(function(err, users){
 console.log('users : ', users);
 console.log('err', err);
 return res.send(users);
});
于 2021-06-15T09:57:53.473 に答える
-1

you can also do it by async function to get all the users

await User.find({},(err,users)=>{

    if (err){
    return  res.status(422).send(err)
    }

    if (!users){
        return res.status(422).send({error:"No data in the collection"})
    }

    res.send({Allusers:users})

})
于 2021-01-13T16:21:53.080 に答える