Javascript Mongoose:获取完整的用户列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14103615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 15:43:52  来源:igfitidea点击:

Mongoose: Get full list of users

javascriptnode.jsmongodbmongoose

提问by Randomblue

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

我尝试使用 Mongoose 发送所有用户的列表,如下所示:

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 findalternative with slightly different semantics, where I could do the following?

当然,res.send(users);是要发送{},这不是我想要的。是否有find语义略有不同的替代方案,我可以在其中执行以下操作?

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.

本质上,我希望只有在从数据库中获取所有用户时才执行回调。

回答by soulcheck

Well, if you really want to return a mapping from _idto user, you could always do:

好吧,如果你真的想从_idto返回一个映射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()returns all matching documents in an array, so your last code snipped sends that array to the client.

find()返回数组中的所有匹配文档,因此您最后剪下的代码将该数组发送到客户端。

回答by bstory

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

在您的视图中,您可以使用变量 users 遍历数据

回答by Evan P

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

这只是对@soulcheck 答案的改进,并修复了 forEach 中的错字(缺少右括号);

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

cheers!

干杯!

回答by yasin

There was the very easy way to list your data :

有一种非常简单的方法可以列出您的数据:

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

回答by vithu shaji

Same can be done with async await and arrow function

同样可以使用 async await 和箭头函数来完成

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

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

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

res.send(userMap);

});

回答by gprathour

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

回答by Arda Kazanc?

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

回答by Abdallah Okasha

In case we want to list all documents in Mongoose collectionafter updateor delete

如果我们想要list all documents in Mongoose collection之后updatedelete

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 documentson success instead of just showing success message

这将list all documents成功而不仅仅是showing success message