David Auvray
David Auvray

Reputation: 317

Mongoose find() returns undefined property and strange object

I have a bug that i can't resolve because for the first time it happen to me.

here is my query :

    Pack.find(
            {idclient: clientId }
        )
        .populate({
            path: 'cards',
            options: { sort: { 'position': 1 } }
        })
        . exec(function(err,pack){
            if(err){
                console.log(err);
            }else{

                 ///
                // here are my logs

                callback(pack);
            }
        });

When i try console.log(pack), i can see a strange return with \n

{ __v: 1,\n  _id: 5596a859240cbd3832123b27,\n  grouped: 0,\n  idclient: \'4Z8OrisV2AMLZn_lAAAA\',\n  matId: 5596a859240cbd3832123b26,\n  reversed: 0,\n  roomId: 5596a859e37d7e7099cec1e6,\n  shuffled: 0,\n  type: \'hand\',\n  cards: [ 5596a859240cbd3832123b28, 5596a85c240cbd3832123b5d ],\n  date: Fri Jul 03 2015 17:20:57 GMT+0200 (CEST),\n  iscut: 0 }

usually, i can see a nice formated Json Object.

So, when i try :

console.log(pack.property) => undefined ...

anyone has had this problem ?

Thanks

Upvotes: 0

Views: 2370

Answers (3)

stefanogreg
stefanogreg

Reputation: 121

As Told Model.find() generates an array so here is how I approach the situation:

Kitten.find(function (err, kittens) {
    if (err) return console.error(err);
    kittens.forEach(function(kitten){
       console.log(kitten.name);
    }); 
});

This seems to me the most clear way to access the properties

Upvotes: 0

David Auvray
David Auvray

Reputation: 317

find() returns an array, so use findOne(), thanks to Adam Wysocki.

Sometimes i'm stupid developper .

Upvotes: 0

Adam Wysocki
Adam Wysocki

Reputation: 323

Two parts to this one ...

First, the callback from a Mongoose find returns an array ... findOne will return a single object.

As far as the new lines go, mongoose documents have a toString() helper for console.log. It is likely adding the newlines for readability. Wrap the output in JSON.stringify (ie. console.log(JSON.stringify(pack))) prior to calling console.log and you will see the document as a string without the newlines. -http://mongoosejs.com/docs/api.html#document_Document-toString

Upvotes: 4

Related Questions