Now, to get all users list from the mongoose collection you have to call User. find() with an empty object as the first parameter. It will search for all the documents that match with the filter Object. But when you pass an empty filter, it will match with all the documents and will return all documents.
get('/usersList', function(req, res) { var users = {}; User. find({}, function (err, user) { users[user. _id] = user; }); res. send(users); });
To get a list of all users in the collection, call User. find() with an empty object as the first parameter: const User = mongoose. model('User', Schema({ name: String, email: String })); // Empty `filter` means "match all documents" const filter = {}; const all = await User.
Well, if you really want to return a mapping from _id
to user
, you could always do:
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.
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
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!
There was the very easy way to list your data :
server.get('/userlist' , function (req , res) {
User.find({}).then(function (users) {
res.send(users);
});
});
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);
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With