Eunice Chia Eunice Chia - 3 months ago 12
Node.js Question

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
.

Answer

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