-3

EDIT : Duplicate of : Mongoose find() not returning result


I'm new to nodejs and nosql db.. Today I'm creating an API which read my user collection with two entries :

The collection (with two entries)

The problem is that the result is an empty array :

Result

Here is the code :

The model :

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var UserModelSchema   = new Schema({
    _id: Schema.Types.ObjectId,
    user_id:String,
    age:{ type: Number },
    status:String
});

module.exports = mongoose.model('user', UserModelSchema);

app.js :

//...
var User     = require('./app/models/user');
//...
router.route('/users')
// get all the users 
.get(function(req, res) {
    User.find(function(err, users) {
        if (err)
            res.send(err);

        res.json(users);
    });
});
flofreelance
  • 944
  • 3
  • 14
  • 31
  • 1
    Possible dupe of https://stackoverflow.com/questions/14183611/mongoose-always-returning-an-empty-array-nodejs – JohnnyHK Oct 14 '18 at 17:20

2 Answers2

2

You may want to (even if not necessary) pass the query condition into your find query:

For all users the condition would be: {}

User.find(<condition>, function(err, users) {
            if (err)
                res.send(err);

            res.json(users);
        });

But I found that if the collection was created through some method there is a chance that, your find might not work. Mongoose find() not returning result

This can be the issue. Normal code-wise you are good. I would suggest you to delete of that collection and start by doing inserts from mongoose itself. This will be cleaner

Hope this helps !!

vizsatiz
  • 1,933
  • 1
  • 17
  • 36
  • I still have an empty array as result – flofreelance Oct 14 '18 at 17:13
  • Oh !! Other than this I can't find any issue. Is `users` empty array ? – vizsatiz Oct 14 '18 at 17:15
  • `User.find({}, function(err, users) { if (err) res.send(err); res.json(users); });` Did you do this ? – vizsatiz Oct 14 '18 at 17:16
  • Yes and users is still an empty array – flofreelance Oct 14 '18 at 17:17
  • Can you check your db again, to make sure that there are records in it? And are there any exceptions or errors ? – vizsatiz Oct 14 '18 at 17:19
  • I've checked it again and there are my 2 records inside. I only have a warning when I'm launching "node app.js" : (node:7771) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect. – flofreelance Oct 14 '18 at 17:22
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/181846/discussion-between-vizsatiz-and-ptiflo). – vizsatiz Oct 14 '18 at 17:27
  • 1
    The `` argument isn't required. This probably shouldn't have been accepted. – JohnnyHK Oct 14 '18 at 17:48
0

Try this...

User.find({}, function(err, docs) {}
Vinesh Goyal
  • 607
  • 5
  • 8