Virtuals + Schemaless = undefined

15 views
Skip to first unread message

Hermann Schliederwirte

unread,
Nov 10, 2014, 10:13:50 AM11/10/14
to mongoo...@googlegroups.com

I noticed that if I have the schema defined as Mixed {}, that virtuals won't work.


Schema


var ArtistSchema = mongoose.Schema({
       componists
: {}
});



Object in MongoDB

{
   _id
:1928319237192387,
   componists
:
     
{
        name
: 'George Enescu'
     
}
}



Mongoose Query

var find = function(req, res, next) {

 
return IP.findById(req.params.id, function(err, artist) {

 
if(!artist) {
     res
.status(404).send({
        status
: 'Not Found'
     
});
 
} else if (!err) {
     console
.log(JSON.stringify(artist.componists.name));
 
}
}




Output:

undefined

Expected Output:

George Enescu

However logging artist.componists works, giving back {name:'George Enescu'}

Valeri Karpov

unread,
Nov 10, 2014, 1:19:13 PM11/10/14
to mongoo...@googlegroups.com
How are you defining your virtual? I don't see any virtuals here...

Hermann Schliederwirte

unread,
Nov 10, 2014, 6:55:00 PM11/10/14
to mongoo...@googlegroups.com
ArtistSchema.virtual('componists.familyName').get(function() {

   
return this.componists.split(' ')[1];
}


Valeri Karpov

unread,
Dec 1, 2014, 5:57:17 PM12/1/14
to mongoo...@googlegroups.com
I'd recommend not using `.` in virtual names, there isn't much point, you'd have to access it with artist['componists.familyName'] because virtuals don't handle dots. Also, how are you using this virtual? Your original example doesn't use the virtual at all.
Reply all
Reply to author
Forward
0 new messages