Eunice Chia
Eunice Chia

Reputation: 455

mongoose callback is not an array

In my models I have this

module.exports.getPhotosById = function(userId,callback){
    Photos.findOne({userId:userId},callback);
}

Then in route I do

 Photo.getPhotosById(req.user._id,function(err,result){

    console.log(result);
    console.log(result.length);
  });

The first console output this

{ _id: 325657865435643245,
  userId: '32443564',
  photo: 'abc.jpg',
  caption: 'abc'
}

but why it's not an array? because the second console's output is undefined.

Upvotes: 0

Views: 29

Answers (2)

Meena
Meena

Reputation: 97

findone Returns one document(JSON) that satisfies the specified query criteria

find Returns the array of Objects.

Upvotes: 0

JohnnyHK
JohnnyHK

Reputation: 312115

result is a single document instead of an array because you're calling findOne, not find.

To get all of a user's photo docs, change your method to:

module.exports.getPhotosById = function(userId, callback){
    Photos.find({userId: userId}, callback);
}

Upvotes: 2

Related Questions