How to findAll in mongoosejs?
Asked Answered
A

5

35

My code is like that:

SiteModel.find(
    {},
    function(docs) {
        next(null, { data: docs });
    }
);

but it never returns anything... but if I specify something in the {} then there is one record. so, how to findall?

Affectional answered 30/8, 2011 at 17:49 Comment(0)
K
82

Try this code to debug:

SiteModel.find({}, function(err, docs) {
    if (!err) { 
        console.log(docs);
        process.exit();
    }
    else {
        throw err;
    }
});
Keifer answered 30/8, 2011 at 18:0 Comment(2)
Any ideas why this wouldn't work when I run this from the terminal like node filename.js?Extraterritorial
Note you don't even need the empty curly braces if you are using a then-catch like paradigm.Charmine
O
25

The 2017 Node 8.5 way

try {
  const results = await SiteModel.find({});
  console.log(results);
} catch (err) {
  throw err;
}
Ona answered 25/10, 2017 at 3:34 Comment(0)
D
5

From the documentation:

let result = SiteModel.find({}, function (err, docs) {});

or using async await you can do like this also:

let result = await SiteModel.find({});
Diddle answered 9/5, 2019 at 6:28 Comment(0)
N
2

const result = await SiteModel.find() - Without the {} in the .find() function works as well.

Netti answered 24/10, 2019 at 4:1 Comment(0)
T
0

exports.getAllUsers = (req, res) => { userSchema .find() .then((data) => res.status(200).json({ status: "success", results: data.length, data: { data, }, }) ) .catch((err) => res.status(404).json({ status: "error", message: "Not records found", }) ); };

Transvestite answered 20/3 at 0:5 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Lancashire

© 2022 - 2024 — McMap. All rights reserved.